我正在做一些单元测试,基本上我需要输入流永远阻止。现在,我用这个来构建输入流总是阻止输入流进行测试?
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