JUnit测试用例中的Thread.sleep [英] Thread.sleep in JUnit test case
问题描述
我正在编写一个测试用例来测试对象的行为。
I'm writing a test case to test an object behaviour.
当对象被实例化时,它必须允许调用方法,只允许调用call()如果它在500毫秒内被调用,否则它必须抛出异常。
When the object is instantiated it must allow the call of a method let say call() only if it has been called within 500 ms, otherwise it must throw an exception.
我设计了这样的Junit测试用例:
I designed the Junit test case like this:
@Test(expected = IllegalStateException.class)
public void testCallAfterTimeout() {
MyObject o= new MyObject();
//To ensure the timeout is occurred
Thread.sleep(1000);
o.call();
}
您认为这是一种好习惯还是我应该采用其他方法?
Do you think is a good practice or I should follow another approach?
非常感谢
推荐答案
使用(实际)时间有两个问题在测试用例中:
There are two problems with using (real) time in test cases:
- 这绝不是确定性的。特别是当您正在寻找高精度时,测试用例将在95%的时间内成功。但有时它们会失败,这些是最难调试的类型。请注意,在多线程测试用例中使用
Thread.sleep()
时,这更加困难。 - 带睡眠的测试用例很长一段时间,这将使你的完整测试集运行繁琐。
- It is never really deterministic. Especially when you are looking for high precision, testcases will succeed 95% of the time. But sometimes they fail, these are the hardest types of failure to debug. Note that when using
Thread.sleep()
with in a multithreaded test case this is even more difficult. - Test cases with sleeps take long to run, after a while this will make running your full testset cumbersome.
如果必须,你的方式是可以接受的。但还有其他选择:
If you must, your way is acceptable. But there are other options:
不要使用真正的时钟。而是使用可以从测试用例控制的假(模拟/存根)时钟:
Don't use a real clock. Instead use a fake (mocked/stubbed) clock that you can control from your testcase:
@Test(expected = IllegalStateException.class)
public void testCallAfterTimeout() {
MyObject o= new MyObject();
// Example function that you could make
advanceClock(1000, TimeUnit.MILLISECONDS)
o.call();
}
在您的对象中,您必须注入一个时钟。 MyObject
可能如下所示:
In your object you have to inject a clock. MyObject
could look like this:
class MyObject
{
public MyObject()
{
this(new Clock());
}
// Protected so only the test case can access it
protected MyObject(Clock clock)
{
// Save clock as local variable, store creation time etc.
}
}
在Java 8中,一种机制为此提供了,例如参见 LocalDate.now()
。但你也可以轻松实现自己的安静。
In Java 8 a mechanism for this is provided, see for instance LocalDate.now()
. But you can also implement your own quiet easily.
这篇关于JUnit测试用例中的Thread.sleep的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!