Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do not display stacktrace of thrown exception messages in JUnit test

Tags:

java

junit4

While testing for message value of thrown exception messages like this:

public void mustFailIfTheActionDoesNotExist() {
        try {
            getAction(UUID.randomUUID().toString());

            fail("Must fail if the action does not exists");
        } catch (MyException ex) {
            Assert.assertEquals("Exception generated on action", ex.getMessage());
        }

the exception and their stacktrace are visible on the terminal. As I have hundreds of classes in my project, the terminal just becomes a long list of stacktraces of exception messages.

Is there a way to suppress the stack-trace of exception output to screen/terminal when Junit tests are run?

PS: I don't want to suppress logging for all unit tests, just in specific cases.

like image 815
goelakash Avatar asked Nov 28 '16 07:11

goelakash


People also ask

Can we throw exception in JUnit test?

When using JUnit 4, we can simply use the expected attribute of the @Test annotation to declare that we expect an exception to be thrown anywhere in the annotated test method. In this example, we've declared that we're expecting our test code to result in a NullPointerException.

Why is JUnit test ignored?

Sometimes you may require not to execute a method/code or Test Case because coding is not done fully. For that particular test, JUnit provides @Ignore annotation to skip the test. Ignore all test methods using @Ignore annotation.

What are exceptions in JUnit?

JUnit provides an option of tracing the exception handling of code. You can test whether the code throws a desired exception or not. The expected parameter is used along with @Test annotation.


1 Answers

I'm guessing that the code you are testing is logging an exception and throwing it. Don't do that.

When catching an exception in non-test code, do one of these:

  1. Log the exception and move on
  2. Rethrow the exception without logging it
  3. Wrap the exception and throw the wrapped exception without doing any logging

If you do this, then any exception will get logged at most once.

You also should ensure that all exceptions are logged at the top level of your code. This may require calling Thread.setDefaultUncaughtExceptionHandler() or `Thread.setUncaughtExceptionHandler()

like image 65
NamshubWriter Avatar answered Oct 05 '22 02:10

NamshubWriter