I'm a Lead engineer at Terracotta, Software AG. I have 10+ years of experience with Java, but I also speak other languages, C, C++, Javascript, Coffeescript, PHP, Perl... See my blog to know about my different personal projects! Aurelien is a DZone MVB and is not an employee of DZone and has posted 17 posts at DZone. You can read more from them at their website. View Full User Profile

Unit testing : Asserting that a line was logged by Logback

12.02.2011
| 7015 views |
  • submit to reddit

I encountered a tricky problem today, I was writing a test for which the assertion was onto some function called or not. I couldn’t mock that function as it was part of an external API for which I couldn’t change the real Object to a mocked Object.

There was a solution, checking that this function was logging a particular event or not. So in order to assert that this specific line was logged or not, I added a mocked Appender. (Note: The Appender is the class that will actually do the logging, e.g. ConsoleAppender to log to the console)

I’m using two great libraries here: Mockito and Logback, please refer to my other post explaining how to configure Logback.

Here is the code:

package com.jsoft.test;

import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.Appender;
import org.mockito.ArgumentMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.junit.Test;

import static org.mockito.Matchers.argThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class MyTest {
  private static Logger logger = LoggerFactory.getLogger(MyTest.class);

    @Test
    public void testSomething() {
    ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
    final Appender mockAppender = mock(Appender.class);
    when(mockAppender.getName()).thenReturn("MOCK");
    root.addAppender(mockAppender);

    //... do whatever you need to trigger the log

    verify(mockAppender).doAppend(argThat(new ArgumentMatcher() {
      @Override
      public boolean matches(final Object argument) {
        return ((LoggingEvent)argument).getFormattedMessage().contains("Hey this is the message I want to see");
      }
    }));
  }
}

 

From http://jsoftbiz.wordpress.com/2011/11/29/unit-testing-asserting-that-a-line-was-logged-by-logback/

Published at DZone with permission of Aurelien Broszniowski, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

Jan Willem Janssen replied on Fri, 2011/12/02 - 2:48am

Couldn't you just spy on the external API to verify whether it was called?

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.