今天学习《Spring实战 第4版》中第二章的内容,其中有一处在Spring单元测试中,对控制台的输出进行断言的测试,有一个类已被弃用StandardOutputStreamLog,查阅资料中使用的新的类是org.junit.contrib.java.lang.system包中的SystemOutRule类,其使用的方法有许多注意事项,在此记录并整理一下Spring单元测试对控制台输出如何进行断言测试。

  1. 首先需要在pom中引入依赖,这里给出Maven的设置

由于Junit包中不含有SystemOutRule类,需要引入如下包:

1
2
3
4
5
6
<dependency>
<groupId>com.github.stefanbirkner</groupId>
<artifactId>system-rules</artifactId>
<version>1.16.0</version>
<scope>test</scope>
</dependency>
  1. 在单元测试中的代码编写方法

对于SystemOutRule中的log,需要先进行一次清除,才能保证断言正确:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Test {
/**
* 先实例化一个SystemOutRule对象
*/
@Rule
public final SystemOutRule log = new SystemOutRule().enableLog();

@Test
public void test() {
System.out.println("Hello World");

// 这里注意一定需要先对log对象进行一次清除日志,否则会在getLog时获取到日志内容导致断言报错
log.clearLog();
assertEquals("Hello World", log.getLog());
}
}