如何在单元测试中避免Thread.sleep? [英] 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);
}
}
在这种情况下,RoutingService
在单独的线程中运行,因此在其构造函数中,我们具有以下内容:
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();
问题是RoutingService
更改了objectToRoute
的状态,而这正是我要检查的内容,但这并没有立即发生,因此测试失败.但是,如果我添加Thread.sleep()
则可以,但是据我所知,这是一种不好的做法.
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.
在这种情况下如何避免Thread.sleep()
?
How can I avoid Thread.sleep()
in this case?
推荐答案
如果您正在测试方法methodToBeTested
的[单元测试],则应该简单地模拟routingservice
.
您不应该测试任何methodToBeTested
调用的方法.
If you are testing [Unit Test] for the method methodToBeTested
, you should simply mock routingservice
.
You shouldn't be testing any methods that methodToBeTested
calls.
但是,听起来您想测试RoutingService
(您说问题是RoutingService
更改了objectToRoute
的状态,而这正是我要检查的内容").
However, it sounds like you want to test the RoutingService
(you said "The problem is that RoutingService
changes the state of objectToRoute
and this is exactly what I want to check").
要测试RoutingService
方法,应为这些方法编写单独的单元测试.
To test RoutingService
methods, you should write separate unit tests for those methods.
这篇关于如何在单元测试中避免Thread.sleep?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!