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("输出文本。");
[color=darkblue] String s = new String("输出文本。\r\n"); // 注意:控制台的换行,Windows用 '\r\n' 表示,如果其他操作系统有可能是'\n',这是因为每个操作系统对换行有不同的理解和实现。[/color]
assertEquals(s, bytes.toString()); // bytes.toString() 作用是将 bytes内容 转换为字符流
[color=blue]bytes.reset(); //同个方法中有多个System.out.println输出的话,要清除bytes中之前的缓存内容,否则输出叠加。[/color]
System.out.println("输出文本。");
assertEquals(s, bytes.toString()); // bytes.toString() 作用是将 bytes内容 转换为字符流
}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值