假设我有以下应该测试的方法:
@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()
?
原文由 Rufi 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果你正在测试方法
methodToBeTested
的[ 单元测试],你应该简单地模拟routingservice
。您不应该测试
methodToBeTested
调用的任何方法。但是,听起来您想测试
RoutingService
(您说“问题是RoutingService
改变了 的状态,我想要的正是objectToRoute
去检查”)。要测试
RoutingService
方法,您应该为这些方法编写单独的单元测试。