【问题标题】:why does my `main()` doesn't catch exception thrown in a `timer` in a junit test?为什么我的`main()`在junit测试中没有捕捉到`timer`中抛出的异常?
【发布时间】:2023-03-05 18:58:01
【问题描述】:

这是我的主要方法:

public static void main(String... args) throws ClassNotFoundException {
    String[] classAndMethod = args[0].split("#");
    if (helpCmd(args)) {
        printHelpForTest(classAndMethod[1]);
        System.exit(0);
    }

    Result result = runTest(classAndMethod);
    exitIfTimeOutExceptionThrown(result);
    System.exit(result.wasSuccessful() ? 0 : 1);
}

private static void exitIfTimeOutExceptionThrown(Result result) {
    boolean isTimeOut = Iterables.filter(result.getFailures(), CodeBlockTimeOutException.class).iterator().hasNext();
    if (isTimeOut)
    {
        System.exit(2);
    }
}

运行这个junit测试:

    @Test
    public void sendSearchRequest() throws Exception {

...

        setTimeOut();

...
    }

private void setTimeOut() {
    if (criticalBlockTimeOut != null) {
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                throw new CodeBlockTimeOutException();
                //thread.interrupt();

            }
        };
        new Timer().schedule(timerTask, Long.parseLong(criticalBlockTimeOut));
    }
}

为什么我看到我的代码抛出了 CodeBlockTimeOutException 但它永远不会以代码 2 退出?

我怎样才能把它扔到主线程中?

【问题讨论】:

标签: java exception junit runtimeexception error-code


【解决方案1】:

定时器事件发生在另一个线程中。主线程退出没有错误。错误是从另一个记录的。如果出现异常,您应该从计划的作业中设置一些 volatile 标志。在主线程中等待作业完成,然后检查此标志。

看看这里:Waiting for a Timer to finish in JavaJava: Wait for TimerTask to complete before continuing execution

【讨论】:

  • JUnit 不可能在主线程中运行。其他线程对测试环境一无所知。
猜你喜欢
  • 1970-01-01
  • 2021-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多