I want to run the same JUnit tests for different interface implementations. I found a nice solution with the @Parameter option:
public class InterfaceTest{
MyInterface interface;
public InterfaceTest(MyInterface interface) {
this.interface = interface;
}
@Parameters
public static Collection<Object[]> getParameters()
{
return Arrays.asList(new Object[][] {
{ new GoodInterfaceImpl() },
{ new AnotherInterfaceImpl() }
});
}
}
This test would be run twice, first with the GoodInterfaceImpl then with the AnotherInterfaceImpl class. But the problem is I need for most of the testcases a new object. A simplified example:
@Test
public void isEmptyTest(){
assertTrue(interface.isEmpty());
}
@Test
public void insertTest(){
interface.insert(new Object());
assertFalse(interface.isEmpty());
}
If the isEmptyTest is run after the insertTest it fails.
Is there an option to run automatically each testcase with a new instance of an implementation?
BTW: Implementing a clear() or reset()-method for the interface is not really an options since I would not need it in productive code.
Create a factory interface and implementations, possibly only in your test hierarchy if you don't need such a thing in production, and make getParameters()
return a list of factories.
Then you can invoke the factory in a @Before
annotated method to get a new instance of your actual class under test for each test method run.