We want to write tests that assert certain content being logged as a part of an Application Startup. How should we do it ?
1 Answers
The basic approach I would try would be to:
- Create a custom logging appender for your logging framework that confirmed the content you were expecting.
- Ensure your JUnit test runs with that appender, perhaps by it being a part of your test logging configuration, or maybe by dynamically adding it when the test starts.
- Have that JUnit test run your application startup.
- At the end of the JUnit test, check some property on the appender to ensure that it logged what you were expecting, and fail the test if it didn't.
I don't think there's a whole lot of built-in functionality to help you, so you may have to write a bit of this infrastructure yourself unless you can find somebody's library to help. If you're logging logback with slf4j, I wrote some code that makes a custom appender to fail a test if an error is logged for a similar question. You might be able to use it as a starting point for how to dynamically include an appender when running a specific JUnit test. There are also some examples for java.util.Logging and log4j in "How to do a JUnit assert on a message in a logger".
In general, logging statements aren't "core" functionality and are just there to help understand a process, so there's usually not a lot of need to unit test them. You may be better off just testing the results of the application startup are what you're expecting, and not testing separately that it also logs something during the process. Presumably if it starts correctly, it also will run whatever logging is in there. I personally haven't needed to get more sophisticated than just checking that no errors were logged as in that linked answer, but perhaps you have more complicated requirements.