Tag Archives: Spring Framework

Read the application log when testing your Spring application

From time to time I need to check so that a function correctly logs error messages to the application log. Here is one solution using Logback in a Spring application

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.Appender;

import org.mockito.ArgumentMatcher;

import org.slf4j.LoggerFactory;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

@Test
public void shouldWriteErrorMessageToLog() {
  Logger l = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
  Appender mockAppender = mock(Appender.class);
  l.addAppender(mockAppender);

  /*
   * Call function that is expected to write to the application log
   */

  verify(mockAppender).doAppend(argThat(new ArgumentMatcher() {
    @Override
    public boolean matches(final Object argument) {
      return ((LoggingEvent)argument).getMessage().contains("FooBar");
    }
  }));
}

Tested with Spring Boot v2.2.4 and TestNG v6.11