In this recipe, we will stub a void method that doesn't return a value. The trick with void methods is that Mockito assumes that they do nothing by default, so there is no need to explicitly stub them (although you may do it).
If you do not want your void method to execute logic, you need to perform the following steps:
BDDMockito.willNothing().given(mock).methodToStub()
, or in the standard way, call Mockito.doNothing().when(mock).methodToStub()
.given(...)
or when(...)
method, you have to provide the mock object (and not the method call in the case of methods that return values).willThrow
answer will be described in more detail in the next recipe):willThrow(new Exception1()).willNothing().given(personSaver).savePerson(smith);
Then, regardless of the number of personSaver.savePerson(...)
method executions, first an exception will be thrown, and then you will always have no action taken (until it is stubbed again).
What Mockito does internally when you start stubbing using the methods starting with do...(...)
or will...(...)
is that the MockitoCore.doAnswer(...)
method is executed with a proper answer, which, in the case of void methods that don't do anything, is the DoesNothing
answer.
It's worth mentioning that as a result of the execution of the doAnswer(...)
method, we have the Stubber
interface returned, which has several fluent API methods (that return Stubber
itself), for example, the following one:
Stubber doNothing();
It also provides us with a method that returns the stubbed object, the when
method (BDDMockito
delegates method execution to the when
method as well).
<T> T when(T mock);
This is why you can profit from Mockito's fluent API, and when you call the when
method, you have access to the mocked object's methods.
doReturn()
|doThrow()
|doAnswer()
|doNothing()
|doCallRealMethod()
family of methods from http://docs.mockito.googlecode.com/hg/1.9.5/org/mockito/Mockito.html#1218.189.186.109