Mockito - difference between doReturn() and when()
doReturn()
is the perfect solution when working with spies. It skips the execution of the actual method, which might have undesired side-effects. On the flipside, when()
method typically invokes the actual method execution, hence it's optimal when dealing with mocks. Notably, doReturn() finds substantial use with spies or methods that can potentially throw exceptions.
Tap into doReturn() for Stubbing
Stubbing void methods & spies
In a case where you're stubbing void methods or working with Mockito spies, doReturn()
is certainly your weapon of choice. It faithfully omits the actual method execution, a critical action when the actual method could possibly change the state or induce undesirable side effects on your test setup.
Zero Side-effects
Utilizing doReturn()
assures you zero unwanted side effects during stubbing, since the method being stubbed isn't executed. This is very important for methods that tinker with global state or interface with external systems.
Overtaking past exceptions or stubs
You could take advantage of doReturn()
to overrule past stubs that were initially set to throw exceptions, giving you room to adjust your mock's behaviour during your test.
when().thenReturn() for type-safety and readability
While doReturn()
excels at averting side-effects, when().thenReturn()
usually reigns supreme in terms of readability and type safety. This expressly indicates your stubbing intentions and ensures any test setup error is caught at compile time.
Consistency and method chaining
Acing one syntax
For the sake of consistency and simplicity in your test code, it might pay dividends to master one syntax. If your test cases are candid and do not involve spies or methods that can morph state or return side-effects, when().thenReturn()
might be the favoured approach due to its cleanliness and type safety.
Handling exceptions & multiple calls
For methods that return distinct values on successive calls or throw exceptions, acing doReturn().when()
could be quite beneficial.
Enhancing Clean code
Evading Code Smells
One should be wary of overriding stubs as it might hint at a code smell in your test structure. Instead, try to design your tests to be predictive and consistent thereby offering a pleasant testing experience.
Context is Key
In the method chaining order bake use of the one that aligns with your testing scenario. By selecting the correct stubbing method, you minimize your efforts, reduce prone-ness to errors, make testing seamless and enjoyable.
Was this article helpful?