Consider the following simple class hierarchy in Java
class Foo {
protected void someMethod(Bar bar) {
...
}
protected void someOtherMethod(Baz baz) {
...
}
}
class EnhancedFoo extends Foo {
@Override
protected void someMethod(Bar bar) {
...
}
}
I now start writing JUnit unit tests for these two classes. Since the contracts for the method someMethod
are same for both the classes, I need basically exactly the same test methods (concerning the someMethod
method) for both the classes, which leads to code duplication. Doing this for a much richer class hierarchy with multiple overwritten methods, it just feels like inheritance is bad for testability.
Also, even though the method someOtherMethod
is not overridden in ExtendedFoo
, I need to include the pertaining tests for ExtendedFoo
because that is still the contract and this extended class and unit tests should test this.
Is there some other way of organizing hierarchies in Java that is better for testability? Is there some JUnit construct that would help alleviate this problem?