使用 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"
);
}
}
参考
- Gitlab 源码地址: https://github.com/Hakky54/log-captor