40.4.3 OutputCapture

OutputCapture是JUnit的一个Rule,用于捕获System.outSystem.err输出,只需简单的将@Rule注解capture,然后在断言中调用toString()

  1. import org.junit.Rule;
  2. import org.junit.Test;
  3. import org.springframework.boot.test.OutputCapture;
  4. import static org.hamcrest.Matchers.*;
  5. import static org.junit.Assert.*;
  6. public class MyTest {
  7. @Rule
  8. public OutputCapture capture = new OutputCapture();
  9. @Test
  10. public void testName() throws Exception {
  11. System.out.println("Hello World!");
  12. assertThat(capture.toString(), containsString("World"));
  13. }
  14. }