How to intercept SLF4J (with logback) logging via a JUnit test?

后端 未结 8 901
天涯浪人
天涯浪人 2020-12-04 10:52

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

8条回答
  •  执笔经年
    2020-12-04 11:48

    I had problems when testing logs line like: LOGGER.error(message, exception).

    The solution described in http://projects.lidalia.org.uk/slf4j-test/ tries to assert as well on the exception and it is not easy (and in my opinion worthless) to recreate the stacktrace.

    I resolved in this way:

    import org.junit.Test;
    import org.slf4j.Logger;
    import uk.org.lidalia.slf4jext.LoggerFactory;
    import uk.org.lidalia.slf4jtest.TestLogger;
    import uk.org.lidalia.slf4jtest.TestLoggerFactory;
    
    import static org.assertj.core.api.Assertions.assertThat;
    import static org.assertj.core.groups.Tuple.tuple;
    import static uk.org.lidalia.slf4jext.Level.ERROR;
    import static uk.org.lidalia.slf4jext.Level.INFO;
    
    
    public class Slf4jLoggerTest {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(Slf4jLoggerTest.class);
    
    
        private void methodUnderTestInSomeClassInProductionCode() {
            LOGGER.info("info message");
            LOGGER.error("error message");
            LOGGER.error("error message with exception", new RuntimeException("this part is not tested"));
        }
    
    
    
    
    
        private static final TestLogger TEST_LOGGER = TestLoggerFactory.getTestLogger(Slf4jLoggerTest.class);
    
        @Test
        public void testForMethod() throws Exception {
            // when
            methodUnderTestInSomeClassInProductionCode();
    
            // then
            assertThat(TEST_LOGGER.getLoggingEvents()).extracting("level", "message").contains(
                    tuple(INFO, "info message"),
                    tuple(ERROR, "error message"),
                    tuple(ERROR, "error message with exception")
            );
        }
    
    }
    

    This has as well the advantage to not having depend on Hamcrest matchers library.

提交回复
热议问题