Java 获取 System.out.print 的终端输出内容
想写个关于获取终端输出进行比较的单元测试时遇到,记录一下
/**
* 排序工具类
*
* @author AhogeK ahogek@gmail.com
* @since 2023-02-06 18:21:10
*/
public class SortUtil {
private SortUtil() {
throw new IllegalStateException("Utility Class");
}
/**
* 打印数组
*
* @param nums 被打印的数组
*/
public static void printArray(int[] nums) {
System.out.print("[");
for (int i = 0; i < nums.length; i++) {
System.out.print(nums[i]);
if (i != nums.length - 1) {
System.out.print(", ");
}
}
System.out.println("]");
}
}
/**
* 排序测试工具类
*
* @author AhogeK ahogek@gmail.com
* @since 2023-02-06 18:26:05
*/
class SortUtilTest {
@Test
void printArrayTest() {
int[] nums = {1, 2, 3};
// 创建一个 Stream 去获取 System.out 的输出
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
// 用于保存原始的System.out
PrintStream old = System.out;
// 告诉Java使用我们自己的输出流
System.setOut(ps);
// 进行 System.out.print 相关的操作
SortUtil.printArray(nums);
// 恢复原先的输出流
System.out.flush();
System.setOut(old);
// 单元测试
Assertions.assertEquals("[1, 2, 3]\n", baos.toString());
}
}