Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force JUnit to Display Uncaught Exception Stack Traces

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.

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.

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

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);
  }
}

Then we get this:

Tests in error:
  testFoo(bar.Foo): java.lang.NullPointerException

Tests run: 1, Failures: 0, Errors: 1, Skipped: 0

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;
  }
}

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.)

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*?

Thanks.

like image 370
luis.espinal Avatar asked Mar 20 '14 21:03

luis.espinal


1 Answers

Try setting the maven-surefire-plugin's useFile parameter to false. Per the Surefire plugin docs this outputs the test reports to the console.

Also see the trimStackTrace parameter.

like image 190
user944849 Avatar answered Oct 31 '22 10:10

user944849