membersound
membersound

Reputation: 86747

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?
    }
}

Upvotes: 2

Views: 4030

Answers (2)

membersound
membersound

Reputation: 86747

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">

Upvotes: 4

Piotr P. Karwasz
Piotr P. Karwasz

Reputation: 16045

If the underlying SLF4J is Log4j 2.x, as your tags might implicate, you can use a ListAppender, which is contained in the log4j-core's test-jar.

Upvotes: 1

Related Questions