英文:
How to stop main method calling sleep() method, when testing it with Junit?
问题
我正在测试一个包含sleep方法的方法。有什么方法可以停止调用sleep(),因为它会使测试变慢吗?
英文:
I am testing a method which contain sleep in side it.What is the way to stop invoke sleep() as it makes testing slow??
public void fun(Integer timeToWait) {
TimeLimiter timeLimiter = new SimpleTimeLimiter();
try {
timeLimiter.callWithTimeout(() -> {
while (true) {
if (avrageIsAboveThanDesired) {
return true;
}
sleep(ofSeconds(REQUEST_STATUS_CHECK_INTERVAL));
}
}, timeToWait, TimeUnit.MINUTES, true);
} catch (UncheckedTimeoutException e) {
logger.error("Timed out waiting Instances to be in Running State", e);
} catch (WingsException e) {
throw e;
} catch (Exception e) {
throw new InvalidRequestException("Error while waiting Instaces to be in Running State", e);
}
}
答案1
得分: 3
没有简单的方法来做这件事。您有几个选项。
最简单的方法是将REQUEST_STATUS_CHECK_INTERVAL
配置为可配置项,并在测试中将其配置为0
。它可以是被测试类的属性。
sleep(ofSeconds(getSleepInterval()));
在测试中将调用:
testedObject.setSleepInterval(0);
第二个选项是将睡眠调用提取到它自己的类中,该类可以被模拟。
class Sleeper {
void sleep(long milisecs) {
Thread.sleep(milisecs);
}
}
在您的类中,您可以有:
private Sleeper sleeper = new Sleeper(); //以及它的setter,或依赖注入
在函数中:
sleeper.sleep(ofSeconds(REQUEST_STATUS_CHECK_INTERVAL));
在测试中,您可以这样做:
Sleeper mockedSleeper = Mockito.mock(Sleeper.class);
testedObject.setSleeper(mockedSleeper);
英文:
There is no easy way for doing this. You have several options.
The easiest one would be to make the REQUEST_STATUS_CHECK_INTERVAL
configurable and configure it to 0
in tests. It can be a property of the tested class.
sleep(ofSeconds(getSleepInternval()));
In the test would wold call
testedObject.setSleepInterval(0);
Second option would be to extract the sleep call into it's own class that can be mocked.
class Sleeper {
void sleep(long milisecs) {
Thread.sleep(milisecs);
}
}
In your class you would have
private Sleeper sleeper = new Sleeper(); //nd it's setter, or dependency injection
In the function
sleeper.sleep(ofSeconds(REQUEST_STATUS_CHECK_INTERVAL));
And it the test you can do
Sleeper mockedSleeper = Mockito.mock(Sleeper.class);
testedObject.setSleeper(mockedSleeper);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论