Writing a single unit test for multiple implementations of an interface

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

    I'd probably avoid JUnit's parameterized tests (which IMHO are pretty clumsily implemented), and just make an abstract List test class which could be inherited by tests implementations:

    public abstract class ListTestBase<T extends List> {
    
        private T instance;
    
        protected abstract T createInstance();
    
        @Before 
        public void setUp() {
            instance = createInstance();
        }
    
        @Test
        public void testOneThing(){ /* ... */ }
    
        @Test
        public void testAnotherThing(){ /* ... */ }
    
    }
    

    The different implementations then get their own concrete classes:

    class SinglyLinkedListTest extends ListTestBase<SinglyLinkedList> {
    
        @Override
        protected SinglyLinkedList createInstance(){ 
            return new SinglyLinkedList(); 
        }
    
    }
    
    class DoublyLinkedListTest extends ListTestBase<DoublyLinkedList> {
    
        @Override
        protected DoublyLinkedList createInstance(){ 
            return new DoublyLinkedList(); 
        }
    
    }
    

    The nice thing about doing it this way (instead of making one test class which tests all implementations) is that if there are some specific corner cases you'd like to test with one implementation, you can just add more tests to the specific test subclass.

    0 讨论(0)
提交回复
热议问题