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

后端 未结 8 903
天涯浪人
天涯浪人 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:29

    You can use slf4j-test from http://projects.lidalia.org.uk/slf4j-test/. It replaces the entire logback slf4j implementation by it's own slf4j api implementation for tests and provides an api to assert against logging events.

    example:

    
      
        
          maven-surefire-plugin
          
            
              ch.qos.logback:logback-classic
            
          
        
      
    
    
    public class Slf4jUser {
    
        private static final Logger logger = LoggerFactory.getLogger(Slf4jUser.class);
    
        public void aMethodThatLogs() {
            logger.info("Hello World!");
        }
    }
    
    public class Slf4jUserTest {
    
        Slf4jUser slf4jUser = new Slf4jUser();
        TestLogger logger = TestLoggerFactory.getTestLogger(Slf4jUser.class);
    
        @Test
        public void aMethodThatLogsLogsAsExpected() {
            slf4jUser.aMethodThatLogs();
    
            assertThat(logger.getLoggingEvents(), is(asList(info("Hello World!"))));
        }
    
        @After
        public void clearLoggers() {
            TestLoggerFactory.clear();
        }
    }
    

提交回复
热议问题