Ankit Dhingra Ankit Dhingra - 23 days ago 10
Java Question

Ignoring stacktrace when testing for exceptions in Junit

We are testing for exceptions in our unit tests

@Test(expected=IOException.class)
public void test() {
// run some code that throws IOException.
}


The test is passing but as a part of the maven build that runs the test, the stacktrace comes in the console output.
Is there anyway in which this stacktrace can be ignored in the tests.

Answer

There isn't a nice way to do this, and it's not worth it anyway. I assume that the printed stacktrace is coming from the called code, and not from your test code:

public class ExpectedExceptionTest {
  @Test(expected = IOException.class)
  public void test() throws Exception {
    foobar();
  }

  public void foobar() throws IOException {
    try {
      throw new IOException();
    } catch (IOException e) {
      e.printStackTrace(System.err);
      throw e;
    }
  }
}

Here, the stacktrace which appears in the maven build log is coming from the error handling of the method that you're trying to test. You don't want to change this error handling. If the test fails, then you want to know what's happened.

If you change it, then it also complicates the code under test unnecessarily. Apart from this specific test, you always want the stacktrace to appear.

So, can we set System.err to be null, as was suggested elsewhere? No. If you call

System.setErr(null);

Then this will result in a NullPointerException (with the above error handling).

If you use log4j or similar for your logging, then you can have a @Rule which temporarily sets the logging level to INFO so that the exception doesn't appear in your logs. Again, the debug won't appear when you need it most, if the test fails.

I get these exception stacktraces all of the time in my project build output(s). I just accept it and congratulate myself that I'm testing error conditions correctly :-)