As far as I understand, there are two main methods to test a class.
As far as I can tell, the first method is considered to be a bad practice.
but why is that?
For me, Unit Test have 2 main purposes:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.