Stubbing exceptions
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Real dependencies fail: cards are declined, mail servers go down, databases time out. A mock can fail on purpose, on the exact call you choose, so you can test what your class does then.
thenThrow for methods that return values
thenThrow makes a stubbed call throw an exception instead of returning a value: when(call).thenThrow(e). It works for any method that returns a value, such as charge or findById.
Make the payment gateway decline on purpose, then check what placeOrder did and what it did not do.
Example 1 · Payment declined: thenThrow
Runs in: the mockito-lab Maven project (JUnit 5.14.4, Mockito 5.23.0)
// src/test/java/com/shoplite/lab/OrderServiceErrorTest.java (part)// Same @Mock fields, @InjectMocks OrderService and CLEAN_CODE product as before.
@Testvoid paymentDeclined_noStockChangeNoOrderNoEmail() { when(products.findById(9)).thenReturn(Optional.of(CLEAN_CODE)); when(payments.charge(eq(1), any(BigDecimal.class))) .thenThrow(new PaymentDeclinedException("insufficient balance"));
PaymentDeclinedException e = assertThrows(PaymentDeclinedException.class, () -> service.placeOrder(1, 9, 2));
assertEquals("Payment declined: insufficient balance", e.getMessage()); verify(products, never()).updateStock(anyInt(), anyInt()); verify(orders, never()).save(any()); verifyNoInteractions(emails);}[INFO] Running com.shoplite.lab.OrderServiceErrorTest [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.938 s -- in com.shoplite.lab.OrderServiceErrorTest
What this code does
thenThrowmakeschargethrowPaymentDeclinedExceptionfor customer 1 and any amount;assertThrowscatches it and returns it for the message check.never()onupdateStockandsave, plusverifyNoInteractions(emails), prove the service stopped at the payment step: no stock taken, no unpaid order.
The test then checks two things. First, what the caller sees: assertThrows returns the exception, so you can check its type and message. Second, what did not happen: for a declined payment, no stock change, no saved order and no email.
The second part is the reason to test error paths at all. A service that saves the order before charging would pass the first check and fail the second.
doThrow().when() for void methods
doThrow(exception).when(mock).method(args) makes a stubbed call throw, and it works for void methods too: first the action, then the mock, then the call.
when(...) cannot stub a void method. See the compile error first, then the fix.
Example 2 · when() cannot stub a void method
Runs in: the mockito-lab Maven project (JUnit 5.14.4, Mockito 5.23.0)
// Does not compile: when(...) needs a value, and a void method returns nonewhen(emails.sendOrderConfirmation(anyInt(), anyInt(), any())) .thenThrow(new IllegalStateException("SMTP server not reachable"));
// The do-family puts the action first, then the mock, then the calldoThrow(new IllegalStateException("SMTP server not reachable")) .when(emails).sendOrderConfirmation(anyInt(), anyInt(), any());[ERROR] COMPILATION ERROR : [ERROR] /C:/projects/mockito-lab/src/test/java/com/shoplite/lab/OrderServiceErrorTest.java:[61,42] 'void' type not allowed here [INFO] 1 error [INFO] BUILD FAILURE
What this code does
when(...)takes the result of the call as its argument;sendOrderConfirmationreturnsvoid, so there is nothing to pass and javac stops.doThrow(...).when(emails).sendOrderConfirmation(...)names the mock first and the call after, which works for void methods.
Example 3 · Email server down: doThrow on a void method
Runs in: the mockito-lab Maven project (JUnit 5.14.4, Mockito 5.23.0)
// src/test/java/com/shoplite/lab/OrderServiceErrorTest.java (part)// Same @Mock fields, @InjectMocks OrderService and CLEAN_CODE product as before.
@Testvoid emailFails_orderIsStillPlaced() { when(products.findById(9)).thenReturn(Optional.of(CLEAN_CODE)); when(payments.charge(1, new BigDecimal("998.00"))).thenReturn("pay_501"); when(orders.save(any(Order.class))).thenReturn(new Order(17, 1, 9, 2, new BigDecimal("998.00"), "pay_501")); doThrow(new IllegalStateException("SMTP server not reachable")) .when(emails).sendOrderConfirmation(anyInt(), anyInt(), any());
Order order = service.placeOrder(1, 9, 2);
assertEquals(17, order.id()); verify(products).updateStock(9, 28);}[INFO] Running com.shoplite.lab.OrderServiceErrorTest Oct 16, 2026 5:59:33 PM com.shoplite.lab.OrderService placeOrder WARNING: Order 17 placed, email failed: SMTP server not reachable [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.981 s -- in com.shoplite.lab.OrderServiceErrorTest
What this code does
- The mock throws
IllegalStateExceptionwhen the email is sent; the service'stry/catchlogs it. The date line and theWARNINGline are that one log entry fromSystem.Logger. - The test still gets order 17 and sees the stock reduced to 28: the order is kept even though the mail failed.
when(...) needs a method that returns something, because the call is its argument. For a void method such as sendOrderConfirmation, when(emails.sendOrderConfirmation(...)) does not compile: javac reports 'void' type not allowed here. The same family has doReturn, doNothing and doAnswer, and they work for every method.
The email test shows a deliberate design: OrderService catches a failed email and logs a warning, because the customer has already paid. The test proves the order is still returned and the stock still reduced.
Fix the error
Stub a void method
Read the error, then pick the line that fixes it.
This line does not compile. Replace line 2.
Error
error: 'void' type not allowed here
Testing error paths: declined, not found, database down
An error path is what a method does when a dependency or a rule fails: unknown product, not enough stock, payment declined, email failed, database down.
List every way placeOrder can fail and test each one. Two cases follow: a database that is down, and a checked exception that Mockito refuses.
Example 4 · Database down, and a checked exception Mockito refuses
Runs in: the mockito-lab Maven project (JUnit 5.14.4, Mockito 5.23.0)
// src/test/java/com/shoplite/lab/OrderServiceErrorTest.java (part)// Same @Mock fields, @InjectMocks OrderService and CLEAN_CODE product as before.
@Testvoid productRepositoryDown_errorReachesTheCaller() { when(products.findById(9)).thenThrow(new IllegalStateException("database not reachable"));
IllegalStateException e = assertThrows(IllegalStateException.class, () -> service.placeOrder(1, 9, 2));
assertEquals("database not reachable", e.getMessage()); verifyNoInteractions(payments, orders, emails);}
// A checked exception that charge(...) does not declare is refused:@Testvoid checkedExceptionNotDeclared() { when(payments.charge(anyInt(), any())).thenThrow(new IOException("network down"));}[INFO] Running com.shoplite.lab.OrderServiceErrorTest [ERROR] Tests run: 2, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.954 s <<< FAILURE! -- in com.shoplite.lab.OrderServiceErrorTest [ERROR] com.shoplite.lab.OrderServiceErrorTest.checkedExceptionNotDeclared -- Time elapsed: 0.004 s <<< ERROR! org.mockito.exceptions.base.MockitoException: Checked exception is invalid for this method! Invalid: java.io.IOException: network down
What this code does
findByIdthrows, so the exception reaches the caller unchanged andverifyNoInteractionsproves no payment, save or email happened.chargedeclares no checked exceptions, so Mockito refusesIOException: a realPaymentGatewaycould never throw it, and the test would describe an impossible case.
For each one, decide the expected result first: which exception reaches the caller, with which message, and which later steps must not run. A database error in findById should reach the caller unchanged, and nothing else may be touched: verifyNoInteractions(payments, orders, emails).
Mockito refuses a checked exception that the method does not declare. charge has no throws IOException, so thenThrow(new IOException(...)) fails with "Checked exception is invalid for this method!". Throw what the real dependency can throw.
assertThrows (JUnit) and assertThatThrownBy (AssertJ) both work; shoplite-api's tests use AssertJ.Consecutive stubbing and thenAnswer
Consecutive stubbing chains several answers for one call, used in turn: thenThrow(busy).thenReturn("pay_502") throws on the first call and returns pay_502 on the second and every later call.
Make one call fail once and then succeed, and let the mock work out the answer for save.
Example 5 · Declined once, then approved; thenAnswer for save
Runs in: the mockito-lab Maven project (JUnit 5.14.4, Mockito 5.23.0)
// src/test/java/com/shoplite/lab/OrderServiceErrorTest.java (part)// Same @Mock fields, @InjectMocks OrderService and CLEAN_CODE product as before.
@Testvoid declinedThenApproved_secondTryWorks() { when(products.findById(9)).thenReturn(Optional.of(CLEAN_CODE)); when(payments.charge(1, new BigDecimal("499.00"))) .thenThrow(new PaymentDeclinedException("bank server busy")) // 1st call .thenReturn("pay_502"); when(orders.save(any(Order.class))).thenAnswer(call -> { Order toSave = call.getArgument(0); return toSave.withId(18); });
assertThrows(PaymentDeclinedException.class, () -> service.placeOrder(1, 9, 1)); Order order = service.placeOrder(1, 9, 1);
assertEquals(18, order.id()); assertEquals("pay_502", order.paymentId()); assertEquals(new BigDecimal("499.00"), order.total());}[INFO] Running com.shoplite.lab.OrderServiceErrorTest [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.938 s -- in com.shoplite.lab.OrderServiceErrorTest
What this code does
- One chain, two answers: the first
chargethrows "bank server busy", the second returnspay_502. Both orders cost 499.00, so one stubbing covers both calls. thenAnswerreturns the order the service passed in, with id 18, so the total and payment id the test checks were really built byplaceOrder.
Example 6 · Failing doubles by hand: a scripted gateway
import java.math.BigDecimal;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Objects;import java.util.Optional;
// ---------- the code under test (a cut-down OrderService) ----------
record Product(int id, String name, BigDecimal price, int stock) {}
record Order(Integer id, int customerId, int productId, int quantity, BigDecimal total, String paymentId) { Order withId(int newId) { return new Order(newId, customerId, productId, quantity, total, paymentId); }}
interface ProductRepository { Optional<Product> findById(int id);
void updateStock(int productId, int newStock);}
interface OrderRepository { Order save(Order order);
List<Order> findByCustomer(int customerId);}
interface PaymentGateway { String charge(int customerId, BigDecimal amount);}
interface EmailSender { void sendOrderConfirmation(int customerId, int orderId, BigDecimal total);}
class ProductNotFoundException extends RuntimeException { ProductNotFoundException(int productId) { super("Product " + productId + " does not exist."); }}
class OutOfStockException extends RuntimeException { OutOfStockException(String name, int available, int requested) { super("Only " + available + " units of " + name + " are in stock; " + requested + " were requested."); }}
class OrderService { private final ProductRepository products; private final OrderRepository orders; private final PaymentGateway payments; private final EmailSender emails;
OrderService(ProductRepository products, OrderRepository orders, PaymentGateway payments, EmailSender emails) { this.products = products; this.orders = orders; this.payments = payments; this.emails = emails; }
Order placeOrder(int customerId, int productId, int quantity) { Product product = products.findById(productId) .orElseThrow(() -> new ProductNotFoundException(productId)); if (product.stock() < quantity) { throw new OutOfStockException(product.name(), product.stock(), quantity); } BigDecimal total = product.price().multiply(BigDecimal.valueOf(quantity)); String paymentId = payments.charge(customerId, total); products.updateStock(productId, product.stock() - quantity); Order saved = orders.save(new Order(null, customerId, productId, quantity, total, paymentId)); try { emails.sendOrderConfirmation(customerId, saved.id(), total); } catch (RuntimeException e) { System.out.println("WARNING: Order " + saved.id() + " placed, email failed: " + e.getMessage()); } return saved; }}
class PaymentDeclinedException extends RuntimeException { PaymentDeclinedException(String reason) { super("Payment declined: " + reason); }}
// ---------- doubles that fail on purpose ----------
/** Answers come from a script, one per call; the last one repeats (like thenThrow(...).thenReturn(...)). */class ScriptedPaymentGateway implements PaymentGateway { private final List<Object> script; private int call = 0;
ScriptedPaymentGateway(Object... answers) { this.script = List.of(answers); }
public String charge(int customerId, BigDecimal amount) { Object answer = script.get(Math.min(call++, script.size() - 1)); if (answer instanceof RuntimeException e) { throw e; } return (String) answer; }}
class OneProduct implements ProductRepository { int stock = 30;
public Optional<Product> findById(int id) { return Optional.of(new Product(9, "Clean Code", new BigDecimal("499.00"), stock)); }
public void updateStock(int productId, int newStock) { stock = newStock; }}
class SavingOrders implements OrderRepository { final List<Order> saved = new ArrayList<>();
public Order save(Order order) { // like thenAnswer(call -> arg.withId(...)) Order withId = order.withId(18 + saved.size()); saved.add(withId); return withId; }
public List<Order> findByCustomer(int customerId) { return saved; }}
public class ScriptedDoublesDemo { public static void main(String[] args) { System.out.println("1. Payment declined"); OneProduct products = new OneProduct(); SavingOrders orders = new SavingOrders(); PaymentGateway declines = new ScriptedPaymentGateway(new PaymentDeclinedException("insufficient balance")); OrderService service = new OrderService(products, orders, declines, (c, o, t) -> { }); try { service.placeOrder(1, 9, 2); } catch (PaymentDeclinedException e) { System.out.println(" caught: " + e.getMessage()); } System.out.println(" stock " + products.stock + ", orders saved " + orders.saved.size());
System.out.println("2. Email server down (a void method that throws)"); EmailSender brokenMail = (customerId, orderId, total) -> { throw new IllegalStateException("SMTP server not reachable"); }; OrderService service2 = new OrderService(new OneProduct(), new SavingOrders(), new ScriptedPaymentGateway("pay_501"), brokenMail); Order placed = service2.placeOrder(1, 9, 2); System.out.println(" order " + placed.id() + " still placed");
System.out.println("3. Declined once, then approved"); SavingOrders orders3 = new SavingOrders(); OrderService service3 = new OrderService(new OneProduct(), orders3, new ScriptedPaymentGateway(new PaymentDeclinedException("bank server busy"), "pay_502"), (c, o, t) -> { }); try { service3.placeOrder(1, 9, 1); } catch (PaymentDeclinedException e) { System.out.println(" try 1: " + e.getMessage()); } Order second = service3.placeOrder(1, 9, 1); System.out.println(" try 2: order " + second.id() + ", " + second.paymentId() + ", Rs " + second.total()); }}1. Payment declined caught: Payment declined: insufficient balance stock 30, orders saved 0 2. Email server down (a void method that throws) WARNING: Order 18 placed, email failed: SMTP server not reachable order 18 still placed 3. Declined once, then approved try 1: Payment declined: bank server busy try 2: order 18, pay_502, Rs 499.00
What this code does
ScriptedPaymentGatewayreturns or throws the next answer from its script and repeats the last one: that is consecutive stubbing.- The email lambda throws, like
doThrowon a void method;SavingOrders.savereturns the passed order with an id, likethenAnswer. - Case 1 shows the state after a decline: stock still 30 and no order saved. Case 2 prints the service's warning and keeps order 18.
thenAnswer(call -> ...) computes the answer when the call happens, from its arguments. call.getArgument(0) is the first argument. For save, returning call.getArgument(0) with a new id behaves like the database, so the test checks what the service really built instead of a value the test made up.
Stubbing the same call twice with when replaces the first answer: the last stubbing wins. Use one chain instead when you mean "first this, then that".
Predict the output
Chained answers
Read the code and pick what it prints.
Round 1 of 2
What do the three calls print?
Next step
Check your understanding
11 quick questions