Vladimir Tikhomirov Vladimir Tikhomirov - 2 months ago 13
Java Question

How to avoid Thread.sleep in Unit tests?

Let's imagine I have the following method which should be tested:

@Autowired
private RoutingService routingservice;

public void methodToBeTested() {
Object objectToRoute = initializeObjectToRoute();
if (someConditions) {
routingService.routeInOneWay(objectToRoute);
} else {
routingService.routeInAnotherWay(objectToRoute);
}
}


In this case
RoutingService
is running in the separate thread, thus in it's constructor we have the following:

Thread thread = new Thread(this);
thread.setDaemon(true);
thread.start();


The problem is that
RoutingService
changes the state of
objectToRoute
and this is exactly what I want to check, but this doesn't happen straight away thus the test fails. However, if I add
Thread.sleep()
then it works, but this is bad practice as I know.

How can I avoid
Thread.sleep()
in this case?

Answer

If you are testing methodToBeTested, you should simply mock routingservice. You shouldn't be testing any methods that methodToBeTested calls. However, it sounds like you want to test the RoutingService (you said "The problem is that RoutingService changes the state of objectToRoute and this is exactly what I want to check"). To test RoutingService methods, you should write separate unit tests for those methods.

Comments