Introduction
If you ever have a situation when testing a void method throw an exception in Mockito using the following code:
it is because the parentheses are placed in the wrong way.
What to do if testing a void method throws an exception in Mockito
In order to fix that problem you need to change:
incorrect parentheses:
to correct one:
According to Mockito's documentation:
The when(obj.method())
cannot be used to stub void methods because the compiler dislikes them when they are enclosed in brackets.
If you wish to stub a void method with an exception, use doThrow():
Conclusion
In this short article, we presented how to get rid of a common mistake in Mockito when a void method throws an exception.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}