junit断言控制台输出之换行符回车符

junit拦截控制台输出,用于测试断言验证System.out.println的输出为预期输出。注意不同颜色标注的代码。

public class TestSystemTool {

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

@org.junit.Before
public void setUp() throws Exception {
//System.out.println("start");
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);
//System.out.println("end");
}
@Test
public void testConsoleOut(){
System.out.println("输出文本。");
String s = new String("输出文本。\r\n");    // 注意:控制台的换行,Windows用 '\r\n' 表示,如果其他操作系统有可能是'\n',这是因为每个操作系统对换行有不同的理解和实现。
assertEquals(s, bytes.toString());          // bytes.toString() 作用是将 bytes内容 转换为字符流
bytes.reset(); //同个方法中有多个System.out.println输出的话,要清除bytes中之前的缓存内容,否则输出叠加。
System.out.println("输出文本。");
assertEquals(s, bytes.toString());          // bytes.toString() 作用是将 bytes内容 转换为字符流
}
}

猜你喜欢

转载自xxqn.iteye.com/blog/2327210