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);

    @Before
    public void setup() {
        when(mockAppender.getName()).thenReturn("MOCK");
        (ch.qos.logback.classic.Logger)LoggerFactory
        .getLogger(ACCESS_LOGGER_NAME))
        .addAppender(mockAppender);
    }

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

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

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

        // when
        object.logSomething();

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

Comments

Popular Posts