【问题标题】:How to define JUnit test time-out at runtime (i.e. without annotations)?如何在运行时定义 JUnit 测试超时(即没有注释)?
【发布时间】:2014-12-15 11:02:36
【问题描述】:

我想运行一个在运行时定义的超时单元测试。我只想为特定测试定义超时,而不是整个班级。

我看到这些是设置超时的方法:

@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方法?

【问题讨论】:

    标签: java unit-testing testing junit timeout


    【解决方案1】:

    添加一个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 对象的任何尝试都为时已晚。

    【讨论】:

    • @EladBenda 你的意思是用@Before注解的方法吗?
    • 是的。但现在我想到了这一点:我实际上只想限制测试中某些行的超时。不是全部。如何自定义?
    • 这里有一个重要的限制——因为这是TestWatcher而不是Timeout,我相信它不能与DisableOnDebug一起使用
    【解决方案2】:

    @Test(timeout=xxx) 不会抛出 TimeoutException,它将导致测试失败。

    您能否更详细地说明您要测试的内容?

    【讨论】:

    • 我想确定测试何时因超时而失败。
    • 请不要发布 cmets 作为答案。如果您没有足够的声誉来发表评论,请解决其他不需要澄清的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-22
    • 2018-12-20
    • 1970-01-01
    • 2021-12-02
    • 2021-12-16
    • 2018-09-20
    相关资源
    最近更新 更多