I have this code and I want to throw an IOException with mockito when the close method inside the try block is called
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);
}
}
}
}
}
This is what I tried inside a test method, but clearly it doesn't work:
OutputStream outputStream = Mockito.mock(OutputStream.class);
doThrow(new IOException()).when(outputStream).close();
cleanup(log, closeables);
How can I accomplish my goal? Thanks!
You need to make sure you pass the mock as 2nd argument to cleanup method.
The following test works for me:
@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
}
The cleanup method looks right. No changes required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With