簡體   English   中英

JUnit4:以多種測試方法測試System.out

[英]JUnit4: Testing System.out in multiple test methods

我有一個應用程序,我想在其中編寫單元測試以測試輸出,然后將其寫入System.out(甚至是System.err)。 每個單獨的測試均按預期工作,但是在同一個類中添加多個測試時,某些測試將失敗,因為JUnit4似乎是多線程的(因此,不能保證在確切重置流時就沒有保證)。 當我將所有測試方法放在自己的類中並使用測試套件時,也會發生相同的情況。

有任何想法嗎?

private static final PrintStream SYS_OUT = System.out;
private static final PrintStream SYS_ERR = System.err;

private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();

@Before
public final void setUpStreams() throws UnsupportedEncodingException {
    System.setOut(new PrintStream(this.outContent, true, CHARSET));
    System.setErr(new PrintStream(this.errContent, true, CHARSET));
}

@After
public final void cleanUpStreams() {
    System.setOut(SYS_OUT);
    System.setErr(SYS_ERR);
}

@Test
public final void listServicesAndMethods() throws ServiceException, UnsupportedEncodingException {
    com.example.Main.main(new String[]{"--list-services"});
    LOG.debug(this.outContent.toString(CHARSET));
    assertTrue("String not found", this.outContent.toString(CHARSET).contains("Some string"));
    assertFalse("Other string found", this.outContent.toString(CHARSET).contains("Some other string"));
    this.outContent.reset();
    this.errContent.reset();
}

編輯:事實證明,失敗的問題不是(僅僅因為?)是因為數據流,而是由於我將選項存儲在主類的靜態字段中。 這樣的結果是,幾個選項在連續測試期間保持活動狀態。 我意識到,在實施了Arian的建議之后,我將第二個類用作實例,而不是調用靜態方法,從而解決了我的問題。

感謝所有答復。

如果尚未這樣做,請重寫應用程序的各個部分以將輸出作為參數,而不是直接寫入System.out 無論測試如何,這通常是更好的設計。

在每個測試中,創建一個新的輸出流(如果需要,還可以監視 System.out )並將其傳遞給被測代碼單元。

暫無
暫無

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

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