I've got a save()
method that returns void
:
public void save( MyThing ) throws SaveFailureException { ... }
The call to save()
has retry logic to handle the exception. I want to test it by mocking out the first call to save()
so that it throws an exception, and the second call should succeed without an exception.
Mockito has a nice way to handle successive behavior for non-void methods, e.g.:
when( mock.save() ).thenThrow( ... ).thenReturn( ... )
How can I do the same with methods that return void?
Mockito provides following methods that can be used to mock void methods. doAnswer() : We can use this to perform some operations when a mocked object method is called that is returning void. doThrow() : We can use doThrow() when we want to stub a void method that throws exception.
For Mockito, there is no direct support to mock private and static methods. In order to test private methods, you will need to refactor the code to change the access to protected (or package) and you will have to avoid static/final methods.
You can do that:
doThrow(...).doNothing().when(mock).voidMethod();
(edit: use doNothing
, as mentioned by @Rogério)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With