23

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?

1 Answer 1

26

You can do that:

doThrow(...).doNothing().when(mock).voidMethod();

(edit: use doNothing, as mentioned by @Rogério)

3
  • 1
    don't you mean: doThrow(...).doReturn(...) ? Jun 10, 2013 at 17:50
  • 3
    It should be doThrow(...).*doNothing()*.when(mock).voidMethod() instead.
    – Rogério
    Jun 11, 2013 at 12:30
  • Nice, I didn't know about doNothing()!
    – fge
    Jun 11, 2013 at 12:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.