如何用一个打印 "root cause first" 堆栈跟踪替换 JUnit 4.12 中的全局异常处理程序?

How to replace the global exception handler in JUnit 4.12 with one printing "root cause first" stack trace?

当我的 JUnit 4.12 测试抛出 Throwable 时,我希望获得出色的 "root cause first" stack trace。我尝试了以下方法,但设置未捕获的异常处理程序无效:

package repro;

import org.junit.Test;
import org.slf4j.LoggerFactory;


public class JavaScratchpadTest
{
  @Test
  public void someTest()
  {
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler()
    {
      public void uncaughtException(Thread t, Throwable e)
      {
        // The root logger is configured to print out the "root cause first" stack trace.
        LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME).error("err: ", e);
      }
    });
    throw new RuntimeException("ex1", new Exception("ex2"));
  }
}

我从堆栈跟踪和 JUnit 源代码检查中推断出一种解决方案可能是提供我自己的解决方案(替换现有的?)RunListener 但我不确定。

您可以定义一个添加 RunListenerRunner,例如

public class MyTestRunner extends BlockJUnit4ClassRunner {

  public MyTestRunner(Class<?> klass) throws InitializationError {
    super(klass);
  }

  @Override
  public void run(RunNotifier notifier) {
    notifier.addListener(new RunListener() {
        @Override
        public void testFailure(Failure failure) throws Exception {
            Throwable exception = failure.getException();
            //insert your logs here
        }
    });
    super.run(notifier);
  }

}

然而,这允许您随心所欲地登录。

您可能也想更改 JUnit 报告。这个好像挺难的,也许反思会有帮助。