How to mock void methods with Mockito
To mock a void method with Mockito, you can use doNothing()
for no action, doThrow()
to simulate exceptions, or doAnswer()
for custom actions. Implement them prior to the when()
method to configure behavior.
When to mock void methods?
At times, mocking void methods seems like trying to listen to a silent song - why do it? Imagine a method that sends an email. During testing, you don't need real emails flying around. But you do need to ensure that the "SendEmail" method was called. That's where doNothing()
, doThrow()
, and doAnswer()
step in.
Handling logical complexity
What if the void method has intricate logic or multiple arguments? Use Answer
interface:
Introducing spies: agents of Mock-land
What if you need only certain behaviors of an object to be mocked and get the rest of the original functionality? Dial Mockito.spy()
:
Chain behavior and verification: keep the naughty methods in check
To impose different behaviors on methods called in sequence, chain doThrow()
and doNothing()
:
For asserting the behavior, use Mockito.verify()
. It's like being the detective on the void-method crime scene:
Isolating tests: Insulate from void method radiations
Your tests need isolation. Imaging there's a radiation-leaking methodWithSideEffects()
:
We obtain insulation from the radiation ... I mean, side effects.
Keep your unit test house tidy
Import Mockito's static methods:
Was this article helpful?