到目前为止,我已经找到了 2 种设置 JUnit 测试超时的方法。要么使用:
@Test(timeout=XXX)
或者使用类似的东西:
@ClassRule
public static Timeout timeoutRule = new Timeout(XXX, TimeUnit.MILLISECONDS);
就我而言,我有一个测试运行程序作为主类来运行我的所有测试套件,因此我可以将测试作为可执行 jar 来执行。 我希望这个运行程序使用反射动态地设置超时。
可以吗?
最佳答案
您可以将超时功能添加到自定义测试运行程序,如下所示:
public class TimeoutTestRunner extends BlockJUnit4ClassRunner {
public TimeoutTestRunner(Class<?> clazz) throws InitializationError {
super(clazz);
}
@Override
protected Statement withPotentialTimeout(FrameworkMethod method, Object test, Statement next) {
return FailOnTimeout.builder()
// you'll probably want to configure/inject this value rather than hardcode it ...
.withTimeout(1, TimeUnit.MILLISECONDS)
.build(next);
}
}
使用此测试运行程序在以下测试用例中进行测试...
@RunWith(TimeoutTestRunner.class)
public class YourTest {
@Test
public void willTimeout() throws InterruptedException {
Thread.sleep(50);
assertTrue(true);
}
@Test
public void willNotTimeout() throws InterruptedException {
assertTrue(true);
}
}
...将表现如下:
-
willTimeout
: 将失败并显示TestTimedOutException
-
willNotTimeout
: 会通过
尽管您需要通过此运行程序运行测试,但您将能够从一个位置控制其超时设置并提供自定义超时派生策略,例如 if test name matches <some regex> then timeout is x else ...
.
关于java - 使用反射设置 JUnit 测试超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46058160/