Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit error testing and logging

Tags:

java

junit

slf4j

I am testing in a JUnit test that a custom error is raised in certain cases, with an @Test annotation, and everything goes well.

 @Test(expected = MyCustomException.class)
 public void MyTest(){
    ...
 }

However, in my code, when I have such an error, I use a logger (slf4j) in such a way :

catch (IllegalArgumentException e) {
        LOG.error("My custom exception occured with {}", inputVar, e);
        throw new MyCustomException(inputVar, e);
    }

So far, the behavior is good. When I build my application with maven, all the tests are done. When the described test is done, the test is marked as passed, but I have a full stacktrace in my shell with a big ERROR in front of it.

My question is the following, is there a way to remove the logs when I run the tests (and therefore not to see it in the shell)?

The second question is : Should I even try to? Or should I just verify that all the tests passed, and not worry about a stack trace and an error when I see one while building my application? (changing my mind instead of changing the code)

like image 736
gvo Avatar asked Sep 29 '25 10:09

gvo


1 Answers

The stacktrace is expected for that test. Therefore, it is fine that it is logged. All works as expected, so I don't think you should change anything. Especially you shouldn't change any code to make the test log look "nicer".

Changing code (maybe some "isTesting" flag) would only obfuscate the code and change the behavior between testing and production and that is exactly what you don't want when doing unit tests.

like image 124
ssindelar Avatar answered Oct 02 '25 05:10

ssindelar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!