This library is useful for testing your logging. It is an SLF4J 2.0.x implementation with mock Loggers backed by Mockito. It uses the new Service Loader mechanism.
(If you still need old SLF4J 1.x implementation with StaticLoggerBinder
,
it is available as version 1.2.1.)
Visit the GitHub Pages site for more.
<dependency>
<groupId>com.ocarlsen.test</groupId>
<artifactId>mock-slf4j-impl</artifactId>
<version>2.0.1-SNAPSHOT</version>
<scope>test</scope>
</dependency>
compile 'com.ocarlsen.test:mock-slf4j-impl:2.0.1-SNAPSHOT'
Consider the class you wish to test:
class MyLoggingClass {
private final Logger logger = LoggerFactory.getLogger(getClass().getSimpleName());
public void loggingMethod() {
logger.debug("this is a debug message");
logger.info("this is an info message");
logger.warn("this is a warn message");
logger.error("this is an error message");
}
}
To confirm the log events, get the mock from the factory and test like this:
@Test
public void testLogging() {
// Given
final MyLoggingClass loggingInstance = new MyLoggingClass();
// When
loggingInstance.loggingMethod();
// Then
final Logger mockLogger = LoggerFactory.getLogger("MyLoggingClass");
final InOrder inOrder = inOrder(mockLogger);
inOrder.verify(mockLogger).debug("this is a debug message");
inOrder.verify(mockLogger).info("this is an info message");
inOrder.verify(mockLogger).warn("this is a warn message");
inOrder.verify(mockLogger).error("this is an error message");
inOrder.verifyNoMoreInteractions();
}
This example is demonstrated in ExampleTest.