How to mock void methods with Mockito while writing unit tests in Java? Some times the method you are unit testing, has a dependency on a method that does not return any value, but has a void return type. To mock such methods we can not use the `when-thenReturn` or `doReturn-when` pattern. Our simple expectation from the `Void` dependency method could be that it throws an exception or does not perform any internal action. Mockito provides two constructs `doThrow-when` and `doNothing-when` to test the above scenarios. Mockito.doThrow(new Exception()).when(mockObject).methodName(); Mockito.doNothing().when(mockObject).methodName(); Let's look at an example to understand the above two scenarios. Let's consider our PersonService class and PersonRepository class. We would be writing unit tests for the `delete()` method of PersonService class. The `delete()` method of PersonService class is dependent on `delete()` method of PersonRepository class, which has return t
Articles on software development