Mockito test a void method throws an exception Mockito test a void method throws an exception java java

Mockito test a void method throws an exception


The parentheses are poorly placed.

You need to use:

doThrow(new Exception()).when(mockedObject).methodReturningVoid(...);                                          ^

and NOT use:

doThrow(new Exception()).when(mockedObject.methodReturningVoid(...));                                                                   ^

This is explained in the documentation


If you ever wondered how to do it using the new BDD style of Mockito:

willThrow(new Exception()).given(mockedObject).methodReturningVoid(...));

And for future reference one may need to throw exception and then do nothing:

willThrow(new Exception()).willDoNothing().given(mockedObject).methodReturningVoid(...));