Mockito thenThrow Exception | Java Fresher Interview
Fast recall
Quick revision
Core answer
Interview-ready guide
Interview answer
To stub a method to throw an exception in Mockito, I'd use when followed by the mock method call, then thenThrow with the exception instance.
For example, when paymentGateway dot charge any then throw new PaymentException connection failed. That makes the mock throw that exception whenever charge is called. Now here's the tricky part: that syntax only works for methods that return something.
If I need to stub a void method, I have to flip the syntax around. Instead of when-then, I use doThrow-when. So it's doThrow new IOException then dot when logger dot log message.
The reason is Java's type system. The when method expects a return value to capture, but void methods don't return anything, so the compiler rejects it. The do-when form handles that.
Once I've stubbed the exception, I verify my code handles it correctly using assertThrows from JUnit. For instance, assertThrows PaymentException dot class comma arrow service dot process order one-L. That confirms the service throws the right exception type.
I'd also check the exception message contains useful information for debugging. One mistake freshers make is only testing the happy path. In production, dependencies fail all the time.
If your repository can throw SQLException, you need a test where it does throw SQLException to verify your service handles it gracefully—maybe by logging the error and returning a user-friendly message instead of crashing the whole application. That separation of concerns is what good exception handling looks like.
Mockito thenThrow Exception | Java Fresher Interview
Direct Answer
Use when(mock.method()).thenThrow(new ExceptionType("message")) to make a mock throw an exception when that method is called. For void methods, use doThrow(new ExceptionType()).when(mock).voidMethod() because when-then syntax doesn't work with void returns. This lets you test error handling logic.
Code Example
@ExtendWith(MockitoExtension.class)
class PaymentServiceTest {
@Mock
private PaymentGateway paymentGateway;
@Mock
private AuditLogger auditLogger;
@InjectMocks
private PaymentService paymentService;
@Test
void shouldHandleGatewayTimeout() {
// Stub non-void method to throw exception
when(paymentGateway.processPayment(any()))
.thenThrow(new GatewayTimeoutException("Connection timed out"));
var exception = assertThrows(PaymentFailedException.class,
() -> paymentService.processOrder(new Order(1L, "Item", 50.0)));
assertThat(exception.getMessage()).contains("Gateway unavailable");
}
@Test
void shouldHandleAuditLogFailure() {
// Stub void method to throw exception using doThrow
doThrow(new IOException("Disk full"))
.when(auditLogger).logTransaction(anyString());
assertDoesNotThrow(() -> paymentService.recordPayment("TXN123"));
}
}
Common Mistakes & Pitfalls
- Only Testing Happy Paths: Writing tests that assume dependencies always succeed. In production, networks fail and databases timeout. If you never test exception handling, you'll ship code that crashes on the first error.
- Using when-thenThrow for Void Methods: Writing when auditLogger dot log transaction any string then throw—this doesn't compile because void methods can't be used with when. Use doThrow dot when auditLogger dot log transaction instead.
- Not Verifying Exception Messages: Catching the exception in a try-catch but not asserting anything about it. Use assertThrows to verify the right exception type is thrown and check its message to ensure meaningful error details are provided.
Check your understanding
Answer these without looking back at the article.
- How do you test that a service wraps a low-level exception in a domain exception?
- How do you test that the service swallows and logs an exception?
- What is the difference between checked and unchecked exception stubbing in Mockito?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.