如何让testng方法在达到超时时立即终止?

qyzbxkaa  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(365)

我必须为一个网站编写测试,这个网站有时在加载页面时会无限期挂起。我想写一个方法,在它开始运行20分钟后超时。
但是当我试着写这样的代码时-

@Test(timeOut=4000)
public void test() {
    try { Thread.sleep(5000); } catch (InterruptedException e) {}
    System.out.println("I don't want this to print.");
}

测试打印出“我不想打印这个”然后以预期的异常失败- org.testng.internal.thread.ThreadTimeoutException: Method didn't finish within the time-out 4000 我怎样才能让考试一到期限就不及格呢?

toe95027

toe950271#

tldr公司;
不要接住 InterruptedException 把它放进去。
当testng工作时(在本例中),框架将创建一个新的单线程executorservice,提交一个等待终止的worker。如果测试运行未完成,工人将抛出 org.testng.internal.thread.ThreadTimeoutException . 相关源代码是:
org.testng.internal.methodinvocationhelper方法调用

private static void invokeWithTimeoutWithNewExecutor(
      ITestNGMethod tm,
      Object instance,
      Object[] parameterValues,
      ITestResult testResult,
      IHookable hookable)
      throws InterruptedException, ThreadExecutionException {
    ExecutorService exec = ThreadUtil.createExecutor(1, tm.getMethodName());

    InvokeMethodRunnable imr =
        new InvokeMethodRunnable(tm, instance, parameterValues, hookable, testResult);
    Future<Void> future = exec.submit(imr);
    exec.shutdown();
    long realTimeOut = MethodHelper.calculateTimeOut(tm);
    boolean finished = exec.awaitTermination(realTimeOut, TimeUnit.MILLISECONDS);

    if (!finished) {
      exec.shutdownNow();
      ThreadTimeoutException exception =
          new ThreadTimeoutException(
              "Method "
                  + tm.getQualifiedName()
                  + "() didn't finish within the time-out "
                  + realTimeOut);
      testResult.setThrowable(exception);
      testResult.setStatus(ITestResult.FAILURE);
    } else {
      Utils.log(
          "Invoker " + Thread.currentThread().hashCode(),
          3,
          "Method " + tm.getMethodName() + " completed within the time-out " + tm.getTimeOut());

      // We don't need the result from the future but invoking get() on it
      // will trigger the exception that was thrown, if any
      try {
        future.get();
      } catch (ExecutionException e) {
        throw new ThreadExecutionException(e.getCause());
      }

      testResult.setStatus(ITestResult.SUCCESS); // if no exception till here then SUCCESS.
    }
  }

关键是:

ExecutorService exec = ThreadUtil.createExecutor(1, tm.getMethodName());
// ... and
boolean finished = exec.awaitTermination(realTimeOut, TimeUnit.MILLISECONDS);

这个 java.util.concurrent.ExecutorService.awaitTermination(...) 方法抛出 InterruptedException 在试验方法中进行了处理。因此,测试方法不会终止,但 finished 标志将为假。
因此,这将有助于:

@Test(timeOut = 4000)
public void test() throws InterruptedException {
    Thread.sleep(5000);
    System.out.println("I don't want this to print");
}

相关问题