Writing a single unit test for multiple implementations of an interface

后端 未结 7 1660
感动是毒
感动是毒 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:01

    I had exactly the same problem and here is my approach with help of JUnit parameterized tests (based on @dasblinkenlight's answer).

    1. Create a base class for the all test classes:
    @RunWith(value = Parameterized.class)
    public class ListTestUtil {
        private Class listClass = null;
    
        public ListTestUtil(Class listClass) {
            this.listClass = listClass;
        }
    
        /**
         * @return a {@link Collection} with the types of the {@link List} implementations.
         */
        @Parameters
        public static Collection> getTypesData() {
            return List.of(MySinglyLinkedList.class, MyArrayList.class);
        }
    
        public  List initList(Object... elements) {
            return initList(Integer.class, elements);
        }
    
        @SuppressWarnings("unchecked")
        public  List initList(Class type, Object... elements) {
            List myList = null;
            try {
                myList = (List) listClass.getDeclaredConstructor().newInstance();
                for (Object el : elements)
                    myList.add(type.cast(el));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return myList;
        }
    }
    
    1. Classes the contain test cases extend ListTestUtil and you can just use initList(...) wherever you want:
    public class AddTest extends ListTestUtil {
        public AddTest(Class cl) {
            super(cl);
        }
    
        @Test
        public void test1() {
            List myList = initList(1, 2, 3);
            // List myList = initList(Strng.class, "a", "b", "c");
            ...
            System.out.println(myList.getClass());
        }
    }
    

    The output proves that the test is called twice - once for each implementation of the list:

    class java.data_structures.list.MySinglyLinkedList
    class java.data_structures.list.MyArrayList
    

提交回复
热议问题