• 使用 LogCaptor 测试 Logging


    背景

    在测试过程中,有的时候我们需要根据打出的日志来判断整个 process flow 是否正确。这就需要用到 LogCaptor

    兼容性

    支持 Java 8 和 Java 11+ 。

    主流的 Logging framework 都支持。

    • SLFJ4
    • Logback
    • Java Util Logging
    • Apache Log4j
    • Apache Log4j2
    • Log4j with Lombok
    • Log4j2 with Lombok
    • SLFJ4 with Lombok
    • Java Util Logging with Lombok

    依赖

    添加 Maven 依赖

    <dependency>
        <groupId>io.github.hakky54</groupId>
        <artifactId>logcaptor</artifactId>
        <version>2.7.0</version>
        <scope>test</scope>
    </dependency>
    

    使用

    服务类,会输出日志:

    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
    
    public class FooService {
        private static final Logger LOGGER = LogManager.getLogger(FooService.class);
        public void sayHello() {
    		// do something 1
            LOGGER.info("process_1 finish");
    		// do something 2
            LOGGER.warn("process_2 finish");
        }
    }
    

    测试类,验证日志信息:

    import static org.assertj.core.api.Assertions.assertThat;
    
    import nl.altindag.log.LogCaptor;
    import org.junit.jupiter.api.Test;
    
    public class FooServiceShould {
    
        @Test
        public void logInfoAndWarnMessages() {
            LogCaptor logCaptor = LogCaptor.forClass(FooService.class);
    
            FooService fooService = new FooService();
            fooService.sayHello();
    
            // Get logs based on level
            assertThat(logCaptor.getInfoLogs()).containsExactly("process_1 finish");
            assertThat(logCaptor.getWarnLogs()).containsExactly("process_2 finish");
    
            // Get all logs
            assertThat(logCaptor.getLogs())
                    .hasSize(2)
                    .contains(
                        "process_1 finish",
                        "process_2 finish"
                    );
        }
    }
    

    参考

  • 相关阅读:
    Scrapy中的POST请求发送和递归爬取
    爬虫之Scrapy框架
    linux下的python3,virtualenv,Mysql,nginx,redis安装配置
    Linu之linux系统基础优化和基本命令
    Linux之linux基础命令2
    Linux之linux基础命令
    Linux之linux入门
    Linux之服务器介绍
    Django之content_type
    Vue.js之路由系统
  • 原文地址:https://www.cnblogs.com/maxstack/p/15500128.html
Copyright © 2020-2023  润新知