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

发表于:2015-10-14 10:46

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:小林觉    来源:51Testing软件测试网采编

  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!\n");    // 注意:控制台的换行,这里用 '\n' 表示
assertEquals(s, bytes.toString());          // bytes.toString() 作用是将 bytes内容 转换为字符流
}
}
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号