[英]Junit test for a output in console
我仍然找不到以下方法的測試方法失敗的原因。
public static void print() {
System.out.println("hello");
}
我的Junit測試方法如下
@Test
public void testPrint(){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
PrintStream old = System.out;
System.setOut(ps);
//execute the above method
obj.print();
System.out.flush();
System.setOut(old);
//test method
String expected = "hello" + "\n";
assertEquals(expected, baos.toString());
}
預期 AssertionFailed 錯誤: <hello but was <hello>
所以問題應該出在換行符上。 有誰知道如何修理它?
像這樣編寫測試是使用模擬的好地方:
// code with Mockito
@Test
public void testPrint(){
PrintStream mockedPrintStream = Mockito.mock(PrintStream.class);
PrintStream old = System.out;
System.setOut(mockedPrintStream);
obj.print();
Mockito.verify(mockedPrintStream).println("hello");
System.setOut(old); // add this line when edit
}
現在你檢查是用參數調用的方法。
Mockito 手冊中有關 mocking 的更多信息
編輯 - 回答評論中的問題
PrintStream old = System.out;
您需要這一行,因為在System.out
中是外部代碼,測試后您應該清理 state 在測試期間污染的所有對象。
在大多數情況下,這種清理發生在@TearDown
方法中,或者只是因為當@Test
方法返回時,GC 刪除了對象。
在這種情況下,您需要在測試方法中手動執行此操作,因為在測試之前沒有其他地方可以將System.out
屬性的 state 恢復為 state。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.