为了账号安全,请及时绑定邮箱和手机立即绑定

println 的 Junit 测试

println 的 Junit 测试

茅侃侃 2023-08-04 18:56:11
我正在尝试为 System.out 编写 junit 测试,尤其是 system.out.println,但即使在阅读了相关帖子后,我也无法找到解决方案。public static void hello(){    System.out.println("Hello");}@Test void Test(){  System.setOut(new PrintStream(outContent));  System.setErr(new PrintStream(errContent));  hello();  assertEquals("Hello\n" , outContent.toString());  System.setIn(System.in);  System.setOut(originalOut);  System.setErr(originalErr);}当我使用 print 而不是 println 并从 assertEquals 中删除 \n 时,它工作得很好,但是每当我尝试使用 println 时,测试都会失败 expected: <Hello> but was: <Hello>org.opentest4j.AssertionFailedError: expected: <Hello> but was: <Hello>甚至错误消息看起来都一样。有什么方法可以使用 println 并通过测试吗?谢谢
查看完整描述

1 回答

?
幕布斯6054654

TA贡献1876条经验 获得超7个赞

问题确实是 Windows 的不同行分隔符,我更新了你的片段,我替换\n为+ System.lineSeparator()


在我的 Mac 本地,它可以正常工作,我希望通过此更改,它在 Windows 上也能正常工作。


public static void hello(){

    System.out.println("Hello");

}



@Test void Test(){

  System.setOut(new PrintStream(outContent));

  System.setErr(new PrintStream(errContent));


  hello();


  // Changed the line below  

  assertEquals("Hello" + System.lineSeparator(), outContent.toString());


  System.setIn(System.in);

  System.setOut(originalOut);

  System.setErr(originalErr);

}


查看完整回答
反对 回复 2023-08-04
  • 1 回答
  • 0 关注
  • 89 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信