Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito different behavior on subsequent calls to a void method?

Tags:

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?

like image 955
Chris Kessel Avatar asked Jun 10 '13 17:06

Chris Kessel


People also ask

How to use Mockito when for void methods?

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.

How to mock private void method using Mockito?

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.


1 Answers

You can do that:

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

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

like image 93
fge Avatar answered Oct 25 '22 18:10

fge