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.
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.
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.
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.
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:
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With