Junit测试时,如何截获到Console的输出

RT:

参考如下Junit 测试代码:

注释部分
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import static org.junit.Assert.*;



public class HelloWorldTest {
    PrintStream console = null;          // 声明(为null):输出流 (字符设备) console
    ByteArrayOutputStream bytes = null;  // 声明(为null):bytes 用于缓存console 重定向过来的字符流
    HelloWorld hello;

    @org.junit.Before
    public void setUp() throws Exception {
        
    	hello = new HelloWorld();
    		
        bytes = new ByteArrayOutputStream();    // 分配空间
        console = System.out;                   // 获取System.out 输出流的句柄

        System.setOut(new PrintStream(bytes));  // 将原本输出到控制台Console的字符流 重定向 到 bytes


    }

    @org.junit.After
    public void tearDown() throws Exception {
        
        System.setOut(console);
    }

    @org.junit.Test
    public void testResult() throws Exception {
    	hello.helloWorld();

    	String s = new String("Hello World! Hello Java!
");    // 注意:控制台的换行,这里用 '
' 表示
        assertEquals(s, bytes.toString());          // bytes.toString() 作用是将 bytes内容 转换为字符流 
    }

}
原文地址:https://www.cnblogs.com/juking/p/4850649.html