假设我有以下应该测试的方法:
@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()
在这种情况下?
我建议等待性 https://github.com/awaitility/awaitility用于同步异步测试。例如,假设您有一个在一些线程操作后设置的结果对象,并且您想要测试它。你这样写声明:
await()
.atMost(100, TimeUnit.SECONDS)
.untilAsserted(() -> assertNotNull(resultObject.getResult()));
它最多等待 100 秒,or直到断言得到满足。例如,如果 getResult() 在 0-100 秒内返回不为 null 的内容,则执行将继续,这与 Thread.sleep 不同,无论结果是否存在,Thread.sleep 都会在给定时间内保留执行。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)