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

Java 如何在运行时定义JUnit测试超时(即没有注释)?,java,unit-testing,testing,junit,timeout,Java,Unit Testing,Testing,Junit,Timeout,我想运行一个带有在运行时定义的超时的单元测试。我只想为一个特定的测试定义一个超时,而不是整个类 我看到以下是设定时间的方法: @Rule public Timeout globalTimeout = new Timeout(10000); // 10 seconds max per method tested 或 但当我运行这段代码时,不会引发异常。 我想确定测试何时因超时而失败 public Timeout testTimeout; private void setTestTimeOut(

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

我看到以下是设定时间的方法:

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

但当我运行这段代码时,不会引发异常。
我想确定测试何时因超时而失败

public Timeout testTimeout;

private void setTestTimeOut() {
    if (!Strings.isNullOrEmpty(testTimeOut)) {
        testTimeout = new Timeout(Integer.parseInt(testTimeOut));
    }
}
如何捕获异常?用
try catch(InterruptException)

包装main方法
@Test(timeout=xxx)
不会抛出
TimeoutException,它会使测试失败


能否更详细地指定要测试的内容?

添加一个
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您的意思是在
之前用
@注释的方法中吗?是的。但现在我想到了这一点:我实际上只想限制测试中某些行的超时。不是全部。如何定制?这里有一个重要的限制-因为这是一个
TestWatcher
而不是
Timeout
,我相信它不能与
DisableOnDebug
一起使用
@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;
  }
};