leop
leop

Reputation: 51

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!

Upvotes: 3

Views: 2980

Answers (2)

Henning Odén
Henning Odén

Reputation: 130

I have done a little bit of research on the usage of doThrow(new Exception()) in the Javadoc Mockito documentation. This passage of the core documentation tells me that in order to have an exception thrown by a stubbed object, the syntax is when(yourStub.method()).doThrow(new Exception()) for functions returning void and when(yourStub.method()).thenThrow(new Exception()) for methods returning anything other than void. In short, the call to configure the throwing of the exception should be when(outputStream.close()).doThrow(new IOException()).

Additionally, you need to pass your outputStream as the second argument into the cleanup function as Petr points out in his answer. Also, the cleanup function might need refactoring to take a single Closable rather than a collection of Closables if you plan to pass a single Closable to it, like you are in your question.

Upvotes: 2

Petr Aleksandrov
Petr Aleksandrov

Reputation: 1504

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.

Upvotes: 3

Related Questions