Search code examples
unit-testingmockingmockitoslf4j

What is the best way to unit-test SLF4J log messages?


I'm using slf4j and I want to unit test my code to make sure that warn/error log messages are generated under certain conditions. I'd rather these be strict unit tests, so I'd prefer not to have to pull up logging configuration from a file in order to test that the log messages are generated. The mocking framework I'm using is Mockito.


Solution

  • I think you could solve your problem with a custom appender. Create a test appender which implements the org.apache.log4j.Appender, and set your appender in the log4j.properties and load it when you execute test cases.

    If you call back to the test harness from that appender you can check the logged messages