Search code examples
javajunitlog4jslf4jspring-boot-test

How to assert org.slf4j.Logger statements with junit?


How can I validate log statements from a org.slf4j.Logger with junit in a spring-boot-test?

@Service
public class MyService {
    private final org.slf4j.Logger LOGGER = org.slf4j.LoggerFactory.getLogger(this.getClass());
    
    public void run() {
        LOGGER.info("running");
    }
}

@SpringBootTest
public class MyTest {
    @Autowired
    private MyService service;

    @Test
    public void test() {
        service.run();
        
        //TODO how to validate log statement?
    }
}

Solution

  • I found a solution with Springs @ExtendWith(OutputCaptureExtension.class):

    @SpringBootTest
    @TestPropertySource(properties = "logging.level.root=INFO")
    public class LogServiceTest {
        private final Logger logger = LoggerFactory.getLogger(getClass());
    
        @Test
        @ExtendWith(OutputCaptureExtension.class)
        public void testLogging(CapturedOutput capture) {
            logger.info("junit"); //can be replaced with any service call that logs
            assertThat(capture.getOut()).contains("junit");
        }
    }
    

    It requires the follow="true" option on your log4j config:

    <Console name="CONSOLE" target="SYSTEM_OUT" follow="true">