核心思路:

  1. 在测试前,将标准输出定向到ByteArrayOutputStream中去
  2. 用输出流文件断言内容
  3. 测试完成,将标准输出修改为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);

     

相关文章:

  • 2021-05-04
  • 2022-12-23
  • 2022-12-23
  • 2021-05-31
  • 2022-12-23
  • 2021-12-18
  • 2021-06-06
  • 2022-01-12
猜你喜欢
  • 2021-12-18
  • 2021-12-25
  • 2021-11-08
  • 2022-12-23
  • 2021-06-25
  • 2021-10-29
  • 2022-12-23
相关资源
相似解决方案