Context: Spring-boot-test provides a lot of libraries which you could use without direct depending on other libraries. It provides a lot of tools which will enable you easily test your web application or any other application. As it provide junit, assertj and much more.
Challenges: Within our application we can create log messages for different use cases. You will see this more often within back-end application. Unfortunately these logging messages are quite tough to test. Spring-boot-test does not provide a tool which will enable you to unit test your log messages.
Solution By adding an additional library to spring-boot-test this use case will be possible:
Usage
To be tested class
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class FooService {
private static final Logger LOGGER = LogManager.getLogger(FooService.class);
public void sayHello() {
LOGGER.info("Keyboard not responding. Press any key to continue...");
LOGGER.warn("Congratulations, you are pregnant!");
}
}
Unit test:
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import ch.qos.logback.classic.Level;
import nl.altindag.log.LogCaptor;
public class FooServiceShould {
@Test
public void logInfoAndWarnMessages() {
String expectedInfoMessage = "Keyboard not responding. Press any key to continue...";
String expectedWarnMessage = "Congratulations, you are pregnant!";
LogCaptor<FooService> logCaptor = LogCaptor.forClass(FooService.class);
FooService fooService = new FooService();
fooService.sayHello();
// Option 1 to assert logging entries
assertThat(logCaptor.getLogs(Level.INFO)).containsExactly(expectedInfoMessage);
assertThat(logCaptor.getLogs(Level.WARN)).containsExactly(expectedWarnMessage);
// Option 2 to assert logging entries
assertThat(logCaptor.getLogs("INFO").containsExactly(expectedInfoMessage);
assertThat(logCaptor.getLogs("WARN").containsExactly(expectedWarnMessage);
// Option 3 to assert logging entries
assertThat(logCaptor.getLogs())
.hasSize(2)
.containsExactly(expectedInfoMessage, expectedWarnMessage);
}
}
What do you think, would this be a good contribute to spring-boot-test library?
Comment From: pivotal-issuemaster
@Hakky54 Please sign the Contributor License Agreement!
Click here to manually synchronize the status of this Pull Request.
See the FAQ for frequently asked questions.
Comment From: pivotal-issuemaster
@Hakky54 Thank you for signing the Contributor License Agreement!
Comment From: snicoll
@Hakky54 thank you for the PR. I assume the intent was that all Spring Boot users would benefit from the library out-of-the-box (optional
is not a transitive scope that doesn't achieve that in your proposal). Given its surface area and community, I am not keen to bring this library for Spring Boot users out-of-the-box. They can certainly do that the same way you did in the PR.
Thanks anyway.
Comment From: Hakky54
Ah too bad that it is not included. Thank you for the feedback, it make sense