问题描述
我有一个接口List
,其实现包括单链接列表,双精度,循环等.我为单精度编写的单元测试应该对大多数双精度以及环形以及接口的任何其他新实现都有利.因此,JUnit不会为每个实现重复执行单元测试,而是提供一些内置的功能,让我进行一个JUnit测试并针对不同的实现运行它吗?
I have an interface List
whose implementations include Singly Linked List, Doubly, Circular etc. The unit tests I wrote for Singly should do good for most of Doubly as well as Circular and any other new implementation of the interface. So instead of repeating the unit tests for every implementation, does JUnit offer something inbuilt which would let me have one JUnit test and run it against different implementations?
使用JUnit参数化测试,我可以提供不同的实现,例如单,双,循环等,但是对于每个实现,都使用相同的对象执行类中的所有测试.
Using JUnit parameterized tests I can supply different implementations like Singly, doubly, circular etc but for each implementation the same object is used to execute all the tests in the class.
推荐答案
在JUnit 4.0+中,您可以使用参数化测试:
With JUnit 4.0+ you can use parameterized tests:
- 在测试装置中添加
@RunWith(value = Parameterized.class)
批注 - 创建一个返回
Collection
的public static
方法,并用@Parameters
进行注释,然后将SinglyLinkedList.class
,DoublyLinkedList.class
,CircularList.class
等放入该集合中 - 向您的测试治具中添加一个采用
Class
:public MyListTest(Class cl)
的构造函数,并将Class
存储在实例变量listClass
中 - 在
setUp
方法或@Before
中,使用List testList = (List)listClass.newInstance();
- Add
@RunWith(value = Parameterized.class)
annotation to your test fixture - Create a
public static
method returningCollection
, annotate it with@Parameters
, and putSinglyLinkedList.class
,DoublyLinkedList.class
,CircularList.class
, etc. into that collection - Add a constructor to your test fixture that takes
Class
:public MyListTest(Class cl)
, and store theClass
in an instance variablelistClass
- In the
setUp
method or@Before
, useList testList = (List)listClass.newInstance();
在完成上述设置后,参数化的运行器将为您在@Parameters
方法中提供的每个子类创建测试夹具MyListTest
的新实例,从而使您可以为所使用的每个子类行使相同的测试逻辑需要测试.
With the above setup in place, the parameterized runner will make a new instance of your test fixture MyListTest
for each subclass that you provide in the @Parameters
method, letting you exercise the same test logic for every subclass that you need to test.
这篇关于为接口的多种实现编写单个单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!