What to do if test a void method throws an exception in Mockito

October 15, 2022 No comments mockito test throw exception

Introduction

If you ever have a situation when testing a void method throw an exception in Mockito using the following code:

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

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:

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

to correct one:

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

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():

doThrow(new RuntimeException()).when(mockedList).clear();

//following throws RuntimeException:
mockedList.clear();

Conclusion

In this short article, we presented how to get rid of a common mistake in Mockito when a void method throws an exception.

{{ message }}

{{ 'Comments are closed.' | trans }}