throw checked Exceptions from mocks with Mockito throw checked Exceptions from mocks with Mockito java java

throw checked Exceptions from mocks with Mockito


Check the Java API for List.
The get(int index) method is declared to throw only the IndexOutOfBoundException which extends RuntimeException.
You are trying to tell Mockito to throw an exception SomeException() that is not valid to be thrown by that particular method call.

To clarify further.
The List interface does not provide for a checked Exception to be thrown from the get(int index) method and that is why Mockito is failing.
When you create the mocked List, Mockito will use the definition of List.class to creates its mock.

The behavior you are specifying with the when(list.get(0)).thenThrow(new SomeException()) doesn't match the method signature in List API, because get(int index) method does not throw SomeException() so Mockito fails.

If you really want to do this, then have Mockito throw a new RuntimeException() or even better throw a new ArrayIndexOutOfBoundsException() since the API specifies that that is the only valid Exception to be thrown.


A workaround is to use a willAnswer() method.

For example the following works (and doesn't throw a MockitoException but actually throws a checked Exception as required here) using BDDMockito:

given(someObj.someMethod(stringArg1)).willAnswer( invocation -> { throw new Exception("abc msg"); });

The equivalent for plain Mockito would to use the doAnswer method


Note that in general, Mockito does allow throwing checked exceptions so long as the exception is declared in the message signature. For instance, given

class BarException extends Exception {  // this is a checked exception}interface Foo {  Bar frob() throws BarException}

it's legal to write:

Foo foo = mock(Foo.class);when(foo.frob()).thenThrow(BarException.class)

However, if you throw a checked exception not declared in the method signature, e.g.

class QuxException extends Exception {  // a different checked exception}Foo foo = mock(Foo.class);when(foo.frob()).thenThrow(QuxException.class)

Mockito will fail at runtime with the somewhat misleading, generic message:

Checked exception is invalid for this method!Invalid: QuxException

This may lead you to believe that checked exceptions in general are unsupported, but in fact Mockito is only trying to tell you that this checked exception isn't valid for this method.