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
I had exactly the same problem and here is my approach with help of JUnit
parameterized tests (based on @dasblinkenlight's answer).
@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;
}
}
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