jeudi 3 décembre 2020

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!

Aucun commentaire:

Enregistrer un commentaire