Capture Logs In Spring Boot Tests

Posted on Oct 11, 2024

To assert that a specific message is logged in a Spring Boot application, the OutputCaptureExtension can be used.

Here’s an example test:

@ExtendWith(OutputCaptureExtension.class)
public class MyServiceTest {

    private MyService myService = new MyService();
    private static final String MESSAGE = "Hello World!";

    @Test
    public void testLogMessage(CapturedOutput output) {
        myService.logMessage(MESSAGE);
        assertThat(output.getOut()).contains(MESSAGE);
    }
}

The CapturedOutput API serves different methods to get the output.