LogCaptor is a library which will enable you to easily capture logging entries for unit testing purposes. It makes it possible to capture and assert SLF4J logs or other logging frameworks logs. It is very leightweight as it contains only one transitive dependency. Most of the developers dont bother testing log messages as it is time consuming and hard to configure. But if it is made really easy, probably more developers would also test their log messages. It should be painless and fun!
Below is an example use case:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FooService {
private static final Logger LOGGER = LoggerFactory.getLogger(FooService.class);
public void sayHello() {
LOGGER.info("Keyboard not responding. Press any key to continue...");
LOGGER.warn("Congratulations, you are pregnant!");
}
}
And the following unit test:
import static org.assertj.core.api.Assertions.assertThat;
import nl.altindag.log.LogCaptor;
import org.junit.jupiter.api.Test;
public class FooServiceShould {
@Test
public void logInfoAndWarnMessages() {
String expectedInfoMessage = "Keyboard not responding. Press any key to continue...";
String expectedWarnMessage = "Congratulations, you are pregnant!";
LogCaptor logCaptor = LogCaptor.forClass(FooService.class);
FooService fooService = new FooService();
fooService.sayHello();
// Option 1 to assert logging entries
assertThat(logCaptor.getInfoLogs()).containsExactly(expectedInfoMessage);
assertThat(logCaptor.getWarnLogs()).containsExactly(expectedWarnMessage);
// Option 2 to assert logging entries
assertThat(logCaptor.getLogs())
.hasSize(2)
.containsExactly(expectedInfoMessage, expectedWarnMessage);
}
}
LogCaptor is a library which will enable you to easily capture logging entries for unit testing purposes. It makes it possible to capture and assert SLF4J logs or other logging frameworks logs. It is very leightweight as it contains only one transitive dependency. Most of the developers dont bother testing log messages as it is time consuming and hard to configure. But if it is made really easy, probably more developers would also test their log messages. It should be painless and fun!
Below is an example use case:
And the following unit test: