如何在运行时(即没有注释)定义JUnit测试超时? [英] How to define JUnit test time-out at runtime (i.e. without annotations)?

查看:154
本文介绍了如何在运行时(即没有注释)定义JUnit测试超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想运行在运行时定义的超时的单元测试.我只想为特定测试而不是整个课程定义超时.

I want to run a unit test with a time-out that is defined at runtime. I want to define a time-out for a specific test only, not the whole class.

我看到了设置超时时间的方法:

I saw these are the ways to set the time out:

@Rule
public Timeout globalTimeout = new Timeout(10000); // 10 seconds max per method tested

@Test(timeout=100) public void infinity() {
   while(true);
}

但是当我运行此代码时,不会引发任何异常. 我想确定由于超时而导致测试失败的时间.

but when I run this code, no exception is thrown. I want to identify when the test failed due to timeout.

public Timeout testTimeout;

private void setTestTimeOut() {
    if (!Strings.isNullOrEmpty(testTimeOut)) {
        testTimeout = new Timeout(Integer.parseInt(testTimeOut));
    }
}

如何捕获异常?用try-catch(InterruptException)包裹主要方法吗?

How can I catch the exception? Wrap the main method with try-catch(InterruptException)?

推荐答案

添加TestWatcher规则,该规则在运行时决定是否应用超时:

Add a TestWatcher rule that decides, at run time, whether to apply a timeout or not:

@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对象的任何尝试都为时已晚.

Your original approach didn't work because JUnit rules take effect before the test code begins to run, so any attempts to adjust your Timeout object within your test are too late.

这篇关于如何在运行时(即没有注释)定义JUnit测试超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆