arrow-rightgithublinkedinscroll-to-topzig-zag

How to test log statements in Spring

Last Updated On

Recently, I discovered a great feature that can help you verify Spring's log statements. It can be used to either check the presence of the log.info statements (including other all types of log levels) as well as assert the content of the log message itself. It's worth noting that this feature is only available since Spring Boot 2.2 and only compatible with Junit 5 since it makes use of @ExtendWith annotation.

Example

Let's assume, we have the following class that is needed to be tested:

@Slf4j
public class AccessService {

    public void requestAccessForData(String name) {
      // ...
      log.info("User " + name + " requested access for data");
      // ...
    }
}

If you're not using Lombok and @Slf4j is not familiar to you, the above snippet would be an equivalent of the following:

public class AccessService {

    private static final Logger log = LoggerFactory.getLogger(AccessService.class);

    public void requestAccessForData(String name) {
      // ...
      log.info("User " + name + " requested access for a data");
      // ...
    }
}

Testing

The following code will assure that a correct log message is produced:

@ExtendWith(OutputCaptureExtension.class)
class AccessServiceTest {

    private final AccessService accessService = new AccessService();

    @Test
    void requestAccessForData(CapturedOutput output) {
        accessService.requestAccessForData("John");
        assertThat(output).contains("User John requested access for a data");
    }
}

Since we use .contains method, it is also possible to verify only specific parts of your logging statement. To check the log level simply add the following line:

assertThat(output.toString()).contains("INFO");

It's not an ideal solution (since the log message may have conflicting output). However, for the majority of cases, it will do the job.

More information and examples can be also found in the official Spring Documentation