Using Mockito with multiple calls to the same method with the same arguments
If you want an identical method to have different outcomes per call with Mockito, use thenReturn
consecutively:
For flexibility and logic-based processing, combine thenReturn
and thenAnswer
:
Each call retrieves the next value, allowing dynamic behaviors.
Advanced usage of Mockito stubbing
To stretch Mockito to its full potential and simulate more intricate scenarios:
Use Answer
for customized behavior
If you want your test to feel alive and change its behavior based on context or even remember past decisions, use the Answer
interface:
Control varied responses for successive calls
If you want to spice up your test's life with a little drama by having different behaviors & even throw exceptions on each call:
Testing void methods with doReturn
In the rare case of testing void methods or spies without the actual method getting triggered:
Cool, huh? It prevents a spy from acting on its own while controlling its behavior.
Use BDD style stubbing with Mockito
The Behavior-Driven Development (BDD) style offers readable structuring for stubbing. Mockito heartily supports this with the BDDMockito
class.
Clear structuring with BDD
Give clear instructions to your mock with exact method call scenarios:
Runtime dynamic stubs with willAnswer
Create mocks that play along with the application behaviour, not against it:
These mocks can react to arguments dynamically, giving a mirror-like reflection of the real application.
Was this article helpful?