java - println 的 Junit 测试
问题描述
我正在尝试为 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 时,它工作得非常好,但是每当我尝试使用 \n 的 println 时,测试都会失败
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);
}
推荐阅读
- flutter - 为什么重建的小部件会出现在原始小部件之外而不是替换它?
- php - SQLSRV_FETCH_ARRAY 未正确返回最后一列
- javascript - js函数在窗口调整大小时重复
- react-native - 通过 CLI 初始化 React Native awsomeProject 时出错
- python - 将python中的一个模块的功能导入同一项目中的另一个模块的最简单/直接的方法是什么?
- reactjs - 使用 getInitialProps 在 Next JS 中将值从服务器端传递到客户端
- visual-studio-code - VS Code 编辑器中 package.json 中的鬼信调试
- c# - 带有 ViewBag 的 DropDownListFor 不传递值
- c++ - 在 C++ 中实现嵌套循环的任何更短的方法?
- excel - Google Places API(附近搜索)不返回结果