For me, Unit Test have 2 main purposes:
- verify the testobject is doing what I expect it to do
- document how to use the tested class correctly
By extending the tested class, the test seams likely to change the classes behaviour. This is bad practic for testing.
Sometimes I even do it to fix for example current time dependency like this if DI is no option:
private InstanceToTest instance;
private Calendar now = new GregorianCalendar(2019, 4, 4, 13, 23, 47);
@Before
public void initInstance() {
instance = new InstanceToTest() {
@Override
Calendar getNow() {
return now;
}
};
}
Now I can test against 4th of April 2019, 13:23:47 to make the test stable.
Sometimes I want to test extracted inner methods separately. I prefer to make these method package private. This way I can call them from my test (if it's in the same package whithin the test source folder) without overwriting them.