假设我有以下应该测试的方法:
@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()
?
最佳答案
如果您正在为方法methodToBeTested
测试[单元测试],您应该简单地模拟routingservice
。
您不应测试 methodToBeTested
调用的任何方法。
但是,听起来您想测试 RoutingService
(您说“问题是 RoutingService
更改了 objectToRoute
的状态并且这正是我想要检查的”)。
要测试 RoutingService
方法,您应该为这些方法编写单独的单元测试。
关于java - 如何在单元测试中避免 Thread.sleep?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36283334/