[英]What is the role of an application provided uncaught exception handler in printing the stack trace?
[英]How to replace the global exception handler in JUnit 4.12 with one printing “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,但我不确定。
您可以定义添加RunListener
的Runner
,例如
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报告。 这似乎很难,也许反思可能会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.