亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 141 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號