簡體   English   中英

JUnit測試System.err.print()

[英]JUnit testing System.err.print()

我有一個簡單的數組類,有一些方法,如Add(int n)AddAt(int n, int index)等。

addAt方法從超類調用另一個方法

public void addAt(int n, int index) {
    if (checkIndex(index, size + 1)){
        ...
    }
}

檢查插入的索引是否不受限制,如果是,超類方法會向控制台輸出錯誤消息。

如果郵件被打印,我應該如何測試? 我正在使用JUnit4.12-beta

@Test
public void testPrint() {
    ByteArrayOutputStream outContent = new ByteArrayOutputStream();
    //redirect the System-output (normaly the console) to a variable
    System.setErr(new PrintStream(outContent));

    //call your method here

    //check if your error message is in the output variable
    assertEquals("your output", outContent.toString());
}

您還可以使用模擬框架來模擬目標對象,並檢查是否已調用目標方法。

例如,請參見http://eclipsesource.com/blogs/2011/10/13/effective-mockito-part-3/

如果您還沒有這樣的框架,這可能是一項投資......

你不能通過提出例外而不是打印信息來簡化你的生活嗎?

在這種情況下,您可以使用“預期”異常,如下所示: 如何斷言在JUnit 4測試中拋出某個異常?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM