我正在嘗試為 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);
}
添加回答
舉報
0/150
提交
取消