How do you mock an exception using Mockito?

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.

Key Points: • For methods with a return type: when(mock.method()).thenThrow(new SomeException()). • For void methods, use doThrow(new SomeException()).when(mock).method() since when()...thenThrow() doesn't work on void calls. • You can throw either an exception class (Mockito instantiates it) or a pre-built exception instance. • Multiple thenThrow() calls chained together throw different exceptions on successive invocations. • This is essential for testing error-handling paths like retries, fallbacks, and catch blocks that are hard to trigger with real dependencies.

Example: 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.

Code Example:

DataRepository repo = mock(DataRepository.class);
when(repo.fetch("id")).thenThrow(new IOException("network error"));

assertThrows(IOException.class, () -> repo.fetch("id"));

Interview Tip: 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."