mardi 29 mars 2016

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?

Aucun commentaire:

Enregistrer un commentaire