OutputCapture
是Spring Boot
提供的一个测试类,其实现了org.junit.rules.TestRule
接口。
它能捕获System.out
和System.err
的输出。使用时直接声明OutputCapture
对象,并使用@Rule
注解标注。在测试方法中使用该对象的toString()
进行断言。
import org.junit.Rule;
import org.junit.Test;
import org.springframework.boot.test.rule.OutputCapture;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
public class MyTest {
@Rule
public OutputCapture capture = new OutputCapture();
@Test
public void testName() throws Exception {
System.out.println("Hello World!");
assertThat(capture.toString(), containsString("World"));
}
}
使用@Rule
注解的字段、方法必须是public
修饰的且为非静态的(即无static
修饰)
官方Demo: spring-boot-sample-xml
官方文档:OutputCapture