首先创建一个ByteArrayOutputStream对象
final static ByteArrayOutputStream outContent = new ByteArrayOutputStream();
由于我的程序是一个控制台小程序,需要测试的控制台输出结果很多,在所有测试方法运行之前更改输出流:
@BeforeClass
public static void setOut(){
System.setOut(new PrintStream(outContent));
}
@BeforeClass表示这个函数在所有测试方法执行之前执行一次(且仅有一次)
在每个测试方法执行之前重置outContent(避免一个方法中的输出对它后面的其它方法产生影响)
@Before
public void resetStream() {
outContent.reset();
}
@Before表示这个函数在每个测试方法执行之前都执行一次
测试时:
assertEquals("expected result", outContent.toString());
如果需要将输出流改回去的话
System.setOut(System.out);