我想运行一个带有运行时定义的超时的单元测试。我只想为特定测试定义超时,而不是为整个类(class)定义超时。
我看到这些是设置超时的方法:
@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)
包裹 main 方法?
最佳答案
添加一个 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
对象的尝试都为时已晚。
关于java - 如何在运行时定义 JUnit 测试超时(即没有注释)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27482585/