SLF4J factory with mock loggers backed by Mockito.
Warning
This library does not support parallel test execution.
Just put a test dependency to your POM:
<dependency>
<artifactId>mock-loggers-slf4j</artifactId>
<groupId>io.github.vitalijr2.logging</groupId>
<scope>test</scope>
<version>1.0.0</version>
</dependency>
The simplest usage example looks like this:
@Test
void helloWorld() {
var helloService = new HelloService();
assertDoesNotThrow(helloService::sayHelloWorld);
verify(LoggerFactory.getLogger(helloService.getClass())).info("Hello World!");
}
See more details at HelloServiceBasicTest.java
Important
Keep in mind that all loggers are initialized only once during the test run.
Therefore, a more complex example cleans the loggers after (or before) each test:
// the static logger instance
private static Logger logger;
// initialize the mock logger once
@BeforeAll
static void setUpClass() {
logger = LoggerFactory.getLogger(HelloService.class);
}
// clean the mock logger after each test
@AfterEach
void tearDown() {
clearInvocations(logger);
}
// use the mock logger in a test
@DisplayName("Names")
@ParameterizedTest(name = "<{0}>")
@ValueSource(strings = {"John", "Jane"})
void names(String name) {
var helloService = new HelloService();
assertDoesNotThrow(() -> helloService.sayHello(name));
var actualLogger = LoggerFactory.getLogger(helloService.getClass());
verify(actualLogger).info("Hello " + name + "!");
verifyNoMoreInteractions(actualLogger);
}
See more details at HelloServiceFullTest.java
To avoid manual cleaning of mock loggers you can use the jUnit extension for automation.
@ExtendWith(MockLoggerExtension.class)
class HelloServiceExtensionTest {
private static Logger logger;
@BeforeAll
static void setUpClass() {
log = LogFactory.getLog(HelloService.class);
}
@DisplayName("Names")
@ParameterizedTest(name = "<{0}>")
@ValueSource(strings = {"John", "Jane"})
void names(String name) {
var helloService = new HelloService();
assertDoesNotThrow(() -> helloService.sayHello(name));
var actualLogger = LoggerFactory.getLogger(helloService.getClass());
verify(actualLogger).info("Hello " + name + "!");
verifyNoMoreInteractions(actualLogger);
}
}
See more details at HelloServiceExtensionTest.java
Also you can use the annotation for automation.
@MockLoggers
class HelloServiceAnnotationTest {
private static Logger logger;
@BeforeAll
static void setUpClass() {
logger = LogFactory.getLog(HelloService.class);
}
@DisplayName("Names")
@ParameterizedTest(name = "<{0}>")
@ValueSource(strings = {"John", "Jane"})
void names(String name) {
var helloService = new HelloService();
assertDoesNotThrow(() -> helloService.sayHello(name));
var actualLogger = LogFactory.getLog(helloService.getClass());
verify(actualLogger).info("Hello " + name + "!");
verifyNoMoreInteractions(actualLogger);
}
}
See more details at HelloServiceAnnotationTest.java