@Mock
private Appender<ILoggingEvent> appender;
@Before
public void setup() {
LOGGER.addAppender(appender);
}
private static final Logger LOGGER = (Logger) LoggerFactory.getLogger(ProductiveImplementation.class);
ProductiveImplementation
is used. Now all logs written in this class can be retrieved by the appender. @Captor
private ArgumentCaptor<ILoggingEvent> logCaptor;
verify(appender, times(1)).doAppend(logCaptor.capture());
doAppend
it capture the written log evnets in the logCaptor
logCaptor
it could also be checked that the log was called in the correct thread. If the log was called in an asynchronously task the verify
needs to be enhanced a little bit:verify(appender, timeout(500).times(1)).doAppend(logCaptor.capture());
verify
will check in the time till the timeout recurring if the method of the appender was called. So if the method is called after 5 milliseconds the test will not wait till the 500 milliseconds are done.assertThat(event.getThreadName()).isNotEqualTo(Thread.currentThread()
.getName());
package com.sap.testapp;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class LoggingIT {
private static final String TEST_MESSAGE = "some test message";
private static final Logger LOGGER = (Logger) LoggerFactory.getLogger(LoggingIT.class);
@Mock
private Appender<ILoggingEvent> appender;
@Captor
private ArgumentCaptor<ILoggingEvent> logCaptor;
@Before
public void setup() {
LOGGER.addAppender(appender);
}
@Test
public void logsAreCaptured() {
logSomeText(); //needs to be replaced by the productive coding call
ILoggingEvent event = getLoggingEvent();
assertThat(event.getMessage()).isEqualTo(TEST_MESSAGE);
assertThat(event.getThreadName()).isEqualTo(Thread.currentThread().getName());
}
private void logSomeText() {
LOGGER.info(TEST_MESSAGE);
LOGGER.debug("other message");
}
private ILoggingEvent getLoggingEvent() {
verify(appender, timeout(500).times(1)).doAppend(logCaptor.capture());
List<ILoggingEvent> loggingEvents = logCaptor.getAllValues();
return loggingEvents.get(0);
}
}
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
User | Count |
---|---|
38 | |
19 | |
13 | |
13 | |
10 | |
10 | |
10 | |
8 | |
8 | |
8 |