Writing a single unit test for multiple implementations of an interface

后端 未结 7 1713
感动是毒
感动是毒 2020-12-23 11:26

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 Do

7条回答
  •  余生分开走
    2020-12-23 12:02

    With JUnit 4.0+ you can use parameterized tests:

    • Add @RunWith(value = Parameterized.class) annotation to your test fixture
    • Create a public static method returning Collection, annotate it with @Parameters, and put SinglyLinkedList.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 the Class in an instance variable listClass
    • In the setUp method or @Before, use List testList = (List)listClass.newInstance();

    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.

提交回复
热议问题