我想运行在运行时定义的超时的单元测试。我只想为一个特定的测试定义一个超时,而不是整个课程。
我看到了以下是设置超时时间的方法:
@Rule
public Timeout globalTimeout = new Timeout(10000); // 10 seconds max per method tested
或者
@Test(timeout=100) public void infinity() {
while(true);
}
但是,当我运行此代码时,不会引发任何异常。我想确定由于超时而导致测试失败的时间。
public Timeout testTimeout;
private void setTestTimeOut() {
if (!Strings.isNullOrEmpty(testTimeOut)) {
testTimeout = new Timeout(Integer.parseInt(testTimeOut));
}
}
如何捕获异常?将主要方法包装为try-catch(InterruptException)
?
添加一个TestWatcher
规则,该规则在运行时决定是否应用超时:
@Rule
public TestWatcher watcher = new TestWatcher() {
@Override
public Statement apply(Statement base, Description description) {
// You can replace this hard-coded test name and delay with something
// more dynamic
if (description.getMethodName().equals("infinity")) {
return new FailOnTimeout(base, 200);
}
return base;
}
};
您的原始方法不起作用,因为JUnit规则在测试代码开始运行之前生效,因此任何Timeout
在测试中调整对象的尝试都为时已晚。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句