How do you mock a method that returns void in Mockito?

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

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()).

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.

Last updated: 16 July 2026

Previous question: What is the difference between mock() and spy() in Mockito?

Next question: What are the use cases for doReturn(), doThrow(), and doAnswer() in Mockito?

More Mockito interview questions

All Mockito questions