我有这段代码,我想在调用 try block 内的 close 方法时用mockito抛出 IOException
public static void cleanup(Logger log, Closeable... closeables) {
for (Closeable c : closeables) {
if (c != null) {
try {
c.close();
} catch (IOException e) {
if (log != null) {
log.warn("Exception in closing " + c, e);
}
}
}
}
}
这是我在测试方法中尝试过的,但显然它不起作用:
OutputStream outputStream = Mockito.mock(OutputStream.class);
doThrow(new IOException()).when(outputStream).close();
cleanup(log, closeables);
我怎样才能实现我的目标?谢谢!
最佳答案
您需要确保将模拟作为第二个参数传递给cleanup
方法。
以下测试对我有用:
@Test
public void testException() throws IOException {
OutputStream outputStream = Mockito.mock(OutputStream.class);
doThrow(new IOException()).when(outputStream).close();
cleanup(log, outputStream);
Mockito.verify(outputStream, times(1)).close(); // make sure #close method is called once
}
cleanup
方法看起来是正确的。无需更改。
关于java - 在方法内部调用方法时模拟异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65130020/