So I've started to layout unit tests for the following bit of code:
public interface MyInterface {
void MyInterfaceMethod1();
void MyInterfaceMethod2();
}
public class MyImplementation1 implements MyInterface {
void MyInterfaceMethod1() {
// do something
}
void MyInterfaceMethod2() {
// do something else
}
void SubRoutineP() {
// other functionality specific to this implementation
}
}
public class MyImplementation2 implements MyInterface {
void MyInterfaceMethod1() {
// do a 3rd thing
}
void MyInterfaceMethod2() {
// do something completely different
}
void SubRoutineQ() {
// other functionality specific to this implementation
}
}
with several implementations and the expectation of more to come.
My initial thought was to save myself time re-writing unit tests with something like this:
public abstract class MyInterfaceTester {
protected MyInterface m_object;
@Setup
public void setUp() {
m_object = getTestedImplementation();
}
public abstract MyInterface getTestedImplementation();
@Test
public void testMyInterfaceMethod1() {
// use m_object to run tests
}
@Test
public void testMyInterfaceMethod2() {
// use m_object to run tests
}
}
which I could then subclass easily to test the implementation specific additional methods like so:
public class MyImplementation1Tester extends MyInterfaceTester {
public MyInterface getTestedImplementation() {
return new MyImplementation1();
}
@Test
public void testSubRoutineP() {
// use m_object to run tests
}
}
and likewise for implmentation 2 onwards.
So my question really is: is there any reason not to do this? JUnit seems to like it just fine, and it serves my needs, but I haven't really seen anything like it in any of the unit testing books and examples I've been reading.
Is there some best practice I'm unwittingly violating? Am I setting myself up for heartache down the road? Is there simply a much better way out there I haven't considered?
Thanks for any help.