核心思路:
- 在测试前,将标准输出定向到ByteArrayOutputStream中去
- 用输出流文件断言内容
- 测试完成,将标准输出修改为console
具体操作示例
- 基本通用复制粘贴操作
public String sep = System.getProperty("line.separator");
public ByteArrayOutputStream out = null;
@Before
public void setUp() throws Throwable{
out = new ByteArrayOutputStream();
System.setOut(new PrintStream(out));
}
@After
public void tearDown() throws Throwable{
out.close();
System.setOut(System.out); //将输出重新设置为控制台输出
}
- 测试部分
String ans = out.toString(); assertEquals(ans, "hello world"+sep);