Mockito: doAnswer Vs thenReturn
When you have a fixed value to return, apply thenReturn()
for clean stubbing:
For a more flexible approach where you need to apply logic to the response, say hello to doAnswer()
:
The art of choosing the suitable stubbing
Static return values? Use thenReturn
thenReturn()
is your reliable friend for consistent stubbing -- it'll dutifully return the same response each time:
Where methods are called multiple times within the same test, thenReturn()
lets you stage dramatic performances by returning different preset values each time:
Stubbing with a dynamic twist using doAnswer
doAnswer()
becomes the protagonist when a dynamic response is your quest. With doAnswer()
, your stub can craft responses based on input like a master chef whipping up custom dishes:
doAnswer()
also allows side quests during method invocation such as modifying state or validating inputs.
Stubbing void methods with doAnswer
doAnswer()
comes to the rescue for void
methods. It allows you to venture through the twisty palaces of methods that change state or generate side effects like incomplete blueprints that still gets the job done:
Spying with doAnswer
When you're spying on objects, doAnswer()
ensures you can stub methods without triggering real behavior. It's a perfect stealth approach to prevent your test cover from being blown:
Unraveling the enigma of doReturn
doReturn()
offers an option to thenReturn()
which is like switching to Easy mode. It's useful when you need to guarantee that a spied method's actual logic does not run while stubbing:
Comprehending through usage twists
Simulating exceptions with doAnswer
doAnswer()
allows you to simulate how your code reacts to exceptions. It's like a simulated war game for your code:
Simulating latency
To simulate slow responses or time delays, doAnswer()
offers a vehicle into the future:
Advanced response logic
When the scenario permits extra computations or external states, doAnswer()
becomes the key to your creative kingdom:
Was this article helpful?