我正在尝试为 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 和\n 时,测试失败并显示
expected: <Hello
> but was: <Hello
>
org.opentest4j.AssertionFailedError: expected: <Hello
> but was: <Hello
>
甚至错误消息看起来都一样。有什么办法可以使用 println 并通过测试吗?谢谢
最佳答案
问题确实是 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);
}
关于java - println 的 Junit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57976700/