Tests your logs using logback

You want to test what your application logging and you don't know how to do that in simplest manner, well we've logback to rescue. (If your using slf4j but with other than logback as a implementation, then you have to add logback as a test dependency with logback.xml in src/test/resources)

One (not exactly) caveat is that, for testing logs using logback we need to use Mockito for creating mock Appnder and asserting for the exact log string in argument.

Here is the actual code-

1. Create a base test class for log testing.
public abstract class BaseLoggerTest {

    final Appender mockAppender = mock(Appender.class);

    public void setup() {

    protected void verifyLog(final String expectedLog, final Level level) {
        verify(mockAppender, atLeastOnce())
        .doAppend(Matchers.argThat(new ArgumentMatcher() {

            public boolean matches(final Object argument) {
                return ((LoggingEvent)argument).getLevel().equals(level)
                    && ((LoggingEvent)argument).getFormattedMessage()
2. Extend logger base class to verify actual logging
public class MyClassLoggerTest extends BaseLoggerTest {

    public void testLogSomethingShouldLogSomething() throws IOException {
        // given
        MyClass object = new MyClass();

        // when

        // then
        verifyLog("I just logged something.", Level.INFO);


Popular Posts