强制JUnit显示未捕获的异常堆栈跟踪 [英] Force JUnit to Display Uncaught Exception Stack Traces
问题描述
可能这在JUnit文档中可能已经很明显,但是似乎找不到它,也不记得我要描述的内容是否有解决方案.
Possibly this might be already obvious in the JUnit docs, but can't seem to find it, nor remember if there is a solution for what I'm about to describe.
当我通过maven(mvn test
)运行测试用例时,标准异常根本不会显示意外异常的堆栈跟踪.我得到的只是一条消息,指示测试失败.
When I'm running my test cases via maven (mvn test
), stack traces of unexpected exceptions are not shown in standard error at all. All I get is a message indicating that a test failed.
如果我的被测代码抛出未检查的异常(例如NPE),则我的测试用例输出看起来像这样:
If my code under test throws an unchecked exception, say a NPE, my test case output looks like this:
Tests in error:
testFoo(bar.Foo)
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
如果我的测试用例声明它可以抛出Exception
对象,那么我将运行时异常包装如下:
If my test case declares it can throw an Exception
object, and I wrap the run-time exception like this:
@Test
public void testFoo() throws Exception
{
try{ // something funky
throw new NullPointerException();
} catch( RuntimeException ex ) {
throw new Exception(ex);
}
}
然后我们得到这个:
Tests in error:
testFoo(bar.Foo): java.lang.NullPointerException
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
现在,我得到的东西几乎没有用.但是,我想看到完整的墨西哥卷饼,整个堆栈的踪迹.但是除了将我的测试用例混入catch/try块中以将堆栈跟踪信息打印到标准错误(难看)之外,我似乎没有找到其他使用JUnit的方法:
Now I'm getting something barely useful. However, I would like to see the full enchilada, the entire stack trace. But I don't seem to find a way to do so with JUnit other than kludging my test cases within a catch/try block to print the stack trace to standard error (ugly):
@Test
public void testFoo() throws Exception
{
try{ // something funky
throw new NullPointerException();
} catch( RuntimeException ex ) {
ex.printStackTrace(); // << this works, but it is ugly.
throw ex;
}
}
我讨厌这样做,因为它会污染(IMO)我的测试用例逻辑;并且它是手动的,我必须在每个测试用例中都这样做(我宁可放上肘部油脂并这样做,这样我就可以在那里获得堆栈跟踪,而不是不需要堆栈跟踪而不必.)
I hate doing this because it pollutes (IMO) my test case logic; and it is manual, and I have to do it for every test case (I rather put the elbow grease and do it so that I get a stack trace right there and there, than to need a stack trace and not have it.)
是否有一种利用/告诉JUnit的方法,以便它打印任何未捕获的异常的堆栈跟踪,而不必*依赖于在我的测试用例代码中明确捕获/打印堆栈跟踪 *?
Is there a way to utilize/tell JUnit so that it prints the stack trace of any uncaught exception without *having to rely on explicitly catching/printing stack traces within my test case code*?
谢谢.
推荐答案
尝试将maven-surefire-plugin的useFile
参数设置为false.根据 Surefire插件文档,这会将测试报告输出到控制台.
Try setting the maven-surefire-plugin's useFile
parameter to false. Per the Surefire plugin docs this outputs the test reports to the console.
另请参阅trimStackTrace
参数.
这篇关于强制JUnit显示未捕获的异常堆栈跟踪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!