java - 如何在运行时定义 JUnit 测试超时(即没有注释)?

标签 java unit-testing testing junit timeout

我想运行一个带有运行时定义的超时的单元测试。我只想为特定测试定义超时,而不是为整个类(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/

相关文章:

unit-testing - 使用 Docker 和依赖注入(inject)框架

visual-studio-2010 - 负载测试结果的问题

unit-testing - 如何单元测试机器控制功能或中间件控制功能

使用防伪和环模拟测试 POST 路由

java - 图像转base64

java - 将 Java 与 Html 或 Html 与 Java 混合

调用方法时出现 Java ClassCastException

Android Studio 代码覆盖率未显示任何 Kotlin 类

java - 如何从GSON解析中确定对象的类?

android - 模拟 Google Analytics v4