carlspring carlspring - 1 month ago 10
Java Question

How to intercept SLF4J logging via a JUnit test?

Is it possible to somehow intercept the logging (SLF4J + logback) and get an

InputStream
(or something else that is readable) via a JUnit test case...?

Answer

You can create a custom appender

public class TestAppender extends AppenderBase<LoggingEvent> {
    static List<LoggingEvent> events = new ArrayList<>();

    @Override
    protected void append(LoggingEvent e) {
        events.add(e);
    }
}

and configure logback-test.xml to use it. Now we can check logging events from our test:

@Test
public void test() {
    ...
    Assert.assertEquals(1, TestAppender.events.size());
    ...
}
Comments