Void methods can't be stubbed with the when()...thenReturn() pattern since there's no return value to chain from, so Mockito provides the doNothing(), doThrow(), and doAnswer() family for them instead.
Key Points: • Use doNothing().when(mock).voidMethod(args) to explicitly make a void call do nothing (this is also the default behavior). • Use doThrow(exception).when(mock).voidMethod(args) to make a void call throw instead. • Use doAnswer(invocation -> {...}).when(mock).voidMethod(args) for custom side effects, like capturing an argument. • The do...().when(mock) order is reversed compared to when(mock)...then...() specifically because void methods have no return value to call when() on. • Since void methods already do nothing by default on a mock, doNothing() is mostly useful for documenting intent or combining with argument matchers.
Example: For a void sendEmail(String to) method on a mocked MailSender, you'd stub failure behavior with doThrow(new MailException("down")).when(mailSender).sendEmail(anyString()).
Code Example:
MailSender mailSender = mock(MailSender.class);
doThrow(new MailException("SMTP down")).when(mailSender).sendEmail(anyString());
assertThrows(MailException.class, () -> mailSender.sendEmail("a@b.com"));Interview Tip: A concise interview answer is:
"Since void methods have nothing to chain when() from, I use the do-family instead: doNothing(), doThrow(), or doAnswer(), followed by .when(mock).method(args). doThrow() is the one I reach for most, to simulate a void method failing."