如何在单元测试中避免Thread.sleep?
2022-09-02 04:40:34
让我们想象一下,我有以下应该测试的方法:
@Autowired
private RoutingService routingservice;
public void methodToBeTested() {
Object objectToRoute = initializeObjectToRoute();
if (someConditions) {
routingService.routeInOneWay(objectToRoute);
} else {
routingService.routeInAnotherWay(objectToRoute);
}
}
在本例中,在单独的线程中运行,因此在其构造函数中,我们有以下内容:RoutingService
Thread thread = new Thread(this);
thread.setDaemon(true);
thread.start();
问题是,它改变了状态,这正是我想要检查的,但这不会立即发生,因此测试失败。但是,如果我添加,那么它有效,但据我所知,这是不好的做法。RoutingService
objectToRoute
Thread.sleep()
在这种情况下,我该如何避免?Thread.sleep()