Mockito lets you make a mocked method throw an exception instead of returning a value, using thenThrow() for non-void methods or doThrow() for void methods.
To test that a service retries once after a transient failure, stub the repository to throw a DataAccessException on the first call and return normally on the second.
DataRepository repo = mock(DataRepository.class);
when(repo.fetch("id")).thenThrow(new IOException("network error"));
assertThrows(IOException.class, () -> repo.fetch("id"));A concise interview answer is
To simulate a failure I use when(mock.method()).thenThrow(exception) for methods with a return value, or doThrow(exception).when(mock).method() for void methods. This lets me exercise error-handling and retry logic without needing the real dependency to actually fail.
Last updated: 16 July 2026
Previous question: How do you verify the behavior of a mock object in Mockito?
Next question: How does ArgumentCaptor work in Mockito? Can you give an example?