3 回答

TA貢獻1780條經驗 獲得超5個贊
您應該保持系統的默認行為,并更改您的斷言代碼:
String EOL = System.getProperty("line.separator")
assertEquals("Some line of text" + EOL, output);
為什么?EOL (end-of-line, or line-separator) 依賴于系統,如果你改變默認行為,你可能會遇到其他奇怪的錯誤。
在您的情況下,您可以在自己的字符串中更改 EOL 就足夠了。
其他(可能不好)方法可能包括:替換所有\r\n和\r到\n并使用\n來比較所有輸出,不使用PrintStream而是自己構建字符串等。

TA貢獻1863條經驗 獲得超2個贊
對于 JUnit 4,系統規則庫有助于此類測試。它也支持行尾規范化。測試看起來像
public class MyTest {
@Rule
public final SystemOutRule systemOutRule = new SystemOutRule().enableLog();
@Test
public void writesTextToSystemOut() {
System.out.print(String.format("Some line of text%n)");
assertEquals(
"Some line of text\n",
systemOutRule.getLogWithNormalizedLineSeparator()
);
}
}
完全披露:我是系統規則的作者。
添加回答
舉報