I am curious if the following example of testing a class with protected
methods is fine.
For example, say you have the following class Foo
that has method a()
of return type Bar
:
class Foo {
protected Bar a() { ... }
// ... other stuff
}
And the following test class TestFoo (using JUnit):
// Question: is extending a source class a bad practice?
class TestFoo extends Foo {
@BeforeAll
public void setup() { /* some setup stuff */ }
@Test
public void testA() {
Bar value = a();
assertEquals(value, ...);
}
}
Also, let's assume that I don't want to use libraries like PowerMockito (say, I don't want to deal with anything that uses Java Reflection API) and I want to keep it really simple. I know there has been a debate on whether to unit-test private methods or not and that can be applied to protected methods, but assuming you want to test this protected method, is this approach correct?
Or am I just crazy?
TestFoo
can't callFoo::a
.protected
.new Foo()
, no problem. But it there are multiple constructors with complex arguments, it adds work (Bar will need a lot of calls tosuper(x,y,z)
) and may be slightly confusing. Also, many classes are final and cannot be extended. I personally think this is a dubious practice, for reasons just like this use case, but others differ.