Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock an exception when calling method inside method

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!

like image 583
leop Avatar asked Aug 06 '26 23:08

leop


1 Answers

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.

like image 200
Petr Aleksandrov Avatar answered Aug 09 '26 11:08

Petr Aleksandrov