Java Thread.currentThread().setUncaughtExceptionHandler()无法与JUNIT一起使用吗? [英] Java Thread.currentThread().setUncaughtExceptionHandler() not working with JUNIT?

查看:96
本文介绍了Java Thread.currentThread().setUncaughtExceptionHandler()无法与JUNIT一起使用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下示例代码中,如果testMethod()通过main()运行,则按预期方式运行,但如果通过JUNIT运行,则不会调用MyUncaughtExceptionHandler.

In the example code below, if the testMethod() is run via main() it works as expected but if it is run via JUNIT then MyUncaughtExceptionHandler does not get called.

对此有一些解释吗?

package nz.co.test;

import java.lang.Thread.UncaughtExceptionHandler;

import org.junit.Test;

public class ThreadDemo {

  private void testMethod() {
    Thread.currentThread().setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());

    Object b = null;
    // Cause a NPE
    b.hashCode();
  }

  @Test
  public void testJunit() {
    // Run via JUnit and MyUncaughtExceptionHandler doesn't catch the Exception
    testMethod(); 
  }

  public static void main(String[] args) {
    // Run via main() works as expected
    new ThreadDemo().testMethod();
  }

  static class MyUncaughtExceptionHandler implements UncaughtExceptionHandler {

    @Override
    public void uncaughtException(Thread t, Throwable e) {
      System.out.println("I caught the exception");
    } 
  }
}

推荐答案

这是因为JUnit捕获并处理了测试中引发的所有异常,因此UncaughtExceptionHandler不会获得任何未捕获的异常.它是在org.junit.runners.ParentRunners中完成的

This is because all exception that are thrown in a test are caught and processed by JUnit, so UncaughtExceptionHandler doesnt get any uncaught exceptions. It is done in org.junit.runners.ParentRunners

...
    protected final void runLeaf(Statement statement, Description description,
            RunNotifier notifier) {
        EachTestNotifier eachNotifier = new EachTestNotifier(notifier, description);
        eachNotifier.fireTestStarted();
        try {
            statement.evaluate();   <-- test method execution is called from here
        } catch (AssumptionViolatedException e) {
            eachNotifier.addFailedAssumption(e);
        } catch (Throwable e) {
            eachNotifier.addFailure(e);
        } finally {
            eachNotifier.fireTestFinished();
        }
    }

这篇关于Java Thread.currentThread().setUncaughtExceptionHandler()无法与JUNIT一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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