我正在做一些單元測試,基本上我需要輸入流永遠阻止。現在,我用這個來構建輸入流總是阻止輸入流進行測試?
InputStream in = new ByteArrayInputStream("".getBytes());
雖然它工作在某些時候,其他時間輸入流輸出流前閱讀(什麼我測試)完成後,會導致所有各種浩劫。
基本上我需要這個輸入流在讀取時永遠阻塞。我能想到的唯一解決方案是使用大量緩衝區設置InputStream,以便其他線程完成,但這是一個非常棘手和脆弱的解決方案。我確實有mockito,但我對它很陌生,並不確定我是否可以在不嘲笑其他任何東西的情況下嘲笑閱讀。
有誰知道更好的解決方案?
編輯:
這是我的新的嘗試。它大部分時間都在工作,但其他時候輸入線程會早死,導致輸出線程死掉(這種行爲是故意的)。我似乎無法弄清楚爲什麼這有時會失敗。
這是TestNG爲簡明起見而進行的一般測試。
protected CountDownLatch inputLatch;
@BeforeMethod
public void botSetup() throws Exception {
//Setup streams for bot
PipedOutputStream out = new PipedOutputStream();
//Create an input stream that we'll kill later
inputLatch = new CountDownLatch(1);
in = new AutoCloseInputStream(new ByteArrayInputStream("".getBytes()) {
@Override
public synchronized int read() {
try {
//Block until were killed
inputLatch.await();
} catch (InterruptedException ex) {
//Wrap in an RuntimeException so whatever was using this fails
throw new RuntimeException("Interrupted while waiting for input", ex);
}
//No more input
return -1;
}
});
Socket socket = mock(Socket.class);
when(socket.getInputStream()).thenReturn(in);
when(socket.getOutputStream()).thenReturn(out);
//Setup ability to read from bots output
botOut = new BufferedReader(new InputStreamReader(new PipedInputStream(out)));
...
}
@AfterMethod
public void cleanUp() {
inputLatch.countDown();
bot.dispose();
}
對於測試我使用readLine()
從botOut得到線的適當數量。但問題是,當輸出線程死亡時,readLine()
永遠阻止掛起TestNG。我已經嘗試了一個混合結果的超時:大部分時間它會工作,但其他人會殺死比正常測試花費的時間稍長的測試。
我唯一的選擇就是不使用流進行這種工作。輸出線程依賴於輸出隊列,所以我可以運行它。但問題是我沒有真正測試寫入流,只是將發送什麼,這會打擾我。
奇怪的是,我將ByteArrayInputStream包裝在BufferedInputStream中,然後覆蓋'read()'以等待CountDownLatch。即使只在@AfterMethod中清理,輸入線程似乎仍然是隨機死亡。所有IO類都依賴'read()'獲取數據嗎?我會說雖然失敗的測試數量已經下降,但問題仍然存在。 – TheLQ
你重寫了所有的read()重載方法嗎? – SJuan76
@SJuan只讀'()',我認爲另一個讀過載取決於'read()' – TheLQ