我想要优秀的"root cause first" stack trace当从我的 JUnit 4.12
测试中抛出 Throwable
时。我尝试了以下方法,但设置未捕获的异常处理程序无效:
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但我不确定。
最佳答案
您可以定义一个 Runner
来添加一个 RunListener
,例如
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 报告。这似乎很难,也许反射(reflection)会有所帮助。
关于java - 如何用一个打印 "root cause first"堆栈跟踪替换 JUnit 4.12 中的全局异常处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32081114/