verify and argument captors
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A method can do its job and return nothing useful: it reduces stock, sends an email, charges a card. How does a test prove those things happened, once, and in the right order?
verify: times(1), never(), atLeastOnce()
verify checks that a mock received a call: verify(mock).method(args) means exactly once, the same as verify(mock, times(1)).
Check the effects placeOrder leaves behind: stock reduced, email sent, and nothing charged for an out-of-stock order.
Example 1 · verify on the happy path and never() on a failure
Runs in: the mockito-lab Maven project (JUnit 5.14.4, Mockito 5.23.0)
// src/test/java/com/shoplite/lab/OrderServiceVerifyTest.java (part)// Same @Mock fields and @InjectMocks OrderService as before, plus:static final Product CLEAN_CODE = new Product(9, "Clean Code", new BigDecimal("499.00"), 30);
@Testvoid placeOrder_reducesStockAndSendsTheEmail() { 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"));
service.placeOrder(1, 9, 2);
verify(products).updateStock(9, 28); // same as times(1) verify(emails, times(1)).sendOrderConfirmation(1, 17, new BigDecimal("998.00"));}
@Testvoid placeOrder_outOfStock_chargesNothingAndSavesNothing() { when(products.findById(9)).thenReturn(Optional.of(CLEAN_CODE));
assertThrows(OutOfStockException.class, () -> service.placeOrder(1, 9, 31));
verify(payments, never()).charge(anyInt(), any()); verify(orders, never()).save(any()); verifyNoInteractions(emails);}[INFO] Running com.shoplite.lab.OrderServiceVerifyTest [INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.947 s -- in com.shoplite.lab.OrderServiceVerifyTest
What this code does
verify(products).updateStock(9, 28)checks the stock effect: 30 - 2 = 28.times(1)on the email check means the same as leaving the mode out.- For 31 copies the service throws before charging, so
never()onchargeandsaveandverifyNoInteractions(emails)all pass. Matchers stand in for "any arguments" here.
Example 2 · Reading two verify failures
Runs in: the mockito-lab Maven project (JUnit 5.14.4, Mockito 5.23.0)
// src/test/java/com/shoplite/lab/VerifyFailuresTest.java (part)// arrange() stubs findById(9), charge(1, 998.00) and save(any(Order.class)) as above.
@Testvoid wrongStock() { arrange(); service.placeOrder(1, 9, 2); verify(products).updateStock(9, 29);}
@Testvoid notCalledAtAll() { when(products.findById(9)).thenReturn(Optional.of(CLEAN_CODE)); try { service.placeOrder(1, 9, 31); } catch (OutOfStockException expected) { // ignore } verify(products).updateStock(9, 28);}[ERROR] com.shoplite.lab.VerifyFailuresTest.wrongStock -- Time elapsed: 0.031 s <<< FAILURE! org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent: Argument(s) are different! Wanted: products.updateStock(9, 29); -> at com.shoplite.lab.VerifyFailuresTest.wrongStock(VerifyFailuresTest.java:48) Actual invocations have different arguments at position [1]: products.findById(9); -> at com.shoplite.lab.OrderService.placeOrder(OrderService.java:24) products.updateStock(9, 28); -> at com.shoplite.lab.OrderService.placeOrder(OrderService.java:31) [ERROR] com.shoplite.lab.VerifyFailuresTest.notCalledAtAll -- Time elapsed: 0.004 s <<< FAILURE! org.mockito.exceptions.verification.WantedButNotInvoked: Wanted but not invoked: products.updateStock(9, 28); -> at com.shoplite.lab.VerifyFailuresTest.notCalledAtAll(VerifyFailuresTest.java:90) However, there was exactly 1 interaction with this mock: products.findById(9); -> at com.shoplite.lab.OrderService.placeOrder(OrderService.java:24)
What this code does
ArgumentsAreDifferent: the method was called, but with(9, 28), not(9, 29). Mockito lists every call onproductswith the line inOrderServicethat made it.WantedButNotInvoked:updateStocknever ran because the order was out of stock; the only call onproductswasfindById(9).
Other verification modes set the count: times(2), never(), atLeastOnce(), atMost(3). Arguments follow the same rules as stubbing: exact values or matchers, all or nothing. Use verify for effects you cannot see in the return value. updateStock(9, 28) and the email are such effects. For a failure path, never() proves the service stopped in time: no payment and no save for an out-of-stock order. verifyNoInteractions(emails) says the mock was not touched at all.
A failed verify prints what was wanted and what really happened, with line numbers. Read the "Actual invocations" part first: it usually shows the bug at once.
Predict the output
Read a failed verify
Read the code and pick what it prints.
Round 1 of 2
Product 9 has stock 30 and the order is for 2. What does Mockito report?
verifyNoMoreInteractions, and when not to use it
verifyNoMoreInteractions(mock) fails the test if the mock received any call that the test did not verify.
It sounds thorough, but it makes tests brittle. This test fails on a call nobody verified.
Example 3 · verifyNoMoreInteractions fails on an unverified call
Runs in: the mockito-lab Maven project (JUnit 5.14.4, Mockito 5.23.0)
// src/test/java/com/shoplite/lab/VerifyFailuresTest.java (part)
@Testvoid noMoreInteractionsOnProducts() { arrange(); service.placeOrder(1, 9, 2); verifyNoMoreInteractions(products); // forgot to verify updateStock first}[ERROR] com.shoplite.lab.VerifyFailuresTest.noMoreInteractionsOnProducts -- Time elapsed: 0.006 s <<< FAILURE! org.mockito.exceptions.verification.NoInteractionsWanted: No interactions wanted here: -> at com.shoplite.lab.VerifyFailuresTest.noMoreInteractionsOnProducts(VerifyFailuresTest.java:97) But found this interaction on mock 'products': -> at com.shoplite.lab.OrderService.placeOrder(OrderService.java:31) *** For your reference, here is the list of all invocations ([?] - means unverified). 1. -> at com.shoplite.lab.OrderService.placeOrder(OrderService.java:24) 2. [?]-> at com.shoplite.lab.OrderService.placeOrder(OrderService.java:31)
What this code does
- Call 1 (
findById, line 24) was stubbed and used, so strict stubs count it as verified. Call 2 (updateStock, line 31) is marked[?]: nobody verified it. - Adding
verify(products).updateStock(9, 28)first makes the test pass, but a refactor that adds one more harmless call would break it again.
With strict stubs, a stubbed call that the code used counts as verified, so only the unverified ones show up (marked [?] in the message). It sounds thorough, but it makes tests brittle: they break whenever the code adds a harmless call, such as a log lookup or a cache read, even though the result is still right. Mockito's own documentation advises against using it in every test.
Use it only when "nothing else happens" is the rule itself, for example "a declined payment must not touch the order repository". There verifyNoInteractions(orders) or never() says it more clearly.
ArgumentCaptor: look at what was passed
An ArgumentCaptor catches the argument of a call during verify, so the test can check its fields.
The service builds an Order and hands it to save. Capture it during verify to look inside.
Example 4 · Capturing the Order passed to save
Runs in: the mockito-lab Maven project (JUnit 5.14.4, Mockito 5.23.0)
// src/test/java/com/shoplite/lab/OrderServiceVerifyTest.java (part)
@CaptorArgumentCaptor<Order> orderCaptor; // or: ArgumentCaptor.forClass(Order.class)
@Testvoid placeOrder_savesANewOrderWithTheComputedTotal() { 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"));
service.placeOrder(1, 9, 2);
verify(orders).save(orderCaptor.capture()); Order toSave = orderCaptor.getValue(); assertNull(toSave.id()); // the repository gives the id assertEquals(2, toSave.quantity()); assertEquals(new BigDecimal("998.00"), toSave.total()); assertEquals("pay_501", toSave.paymentId());}[INFO] Running com.shoplite.lab.OrderServiceVerifyTest [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.947 s -- in com.shoplite.lab.OrderServiceVerifyTest
What this code does
orderCaptor.capture()insideverifystores theOrderthatplaceOrderpassed tosave;getValue()returns it.- The checks cover what the service computed itself: no id yet (the repository gives it), quantity 2, total 998.00 and the payment id from the gateway.
- The stubbed
savereturn value is not checked here: asserting what the stub returns would only test the stub.
Create it with @Captor ArgumentCaptor<Order> orderCaptor; (or ArgumentCaptor.forClass(Order.class)), write verify(orders).save(orderCaptor.capture()), then read orderCaptor.getValue(). This is how you test an object the service builds and hands on, never returns. Here it is the new Order before saving: no id yet, quantity 2, total 998.00, the payment id from the gateway. When a method was called several times, getAllValues() returns every captured argument in order.
capture() is a matcher, so the other arguments of that call must be matchers too: verify(emails).sendOrderConfirmation(eq(1), eq(17), totalCaptor.capture()).
verify, not during when. Stubbing with a captor works but hides which call you meant to check.InOrder: when the sequence matters
InOrder checks that calls happened in a given sequence, even across several mocks: inOrder(payments, orders, emails), then inOrder.verify(...) for each call.
ShopLite must charge before it saves, and send the email last. Verify that sequence.
Example 5 · InOrder: charge, then save, then email
Runs in: the mockito-lab Maven project (JUnit 5.14.4, Mockito 5.23.0)
// src/test/java/com/shoplite/lab/OrderServiceVerifyTest.java (part)
@Testvoid placeOrder_chargesBeforeSavingAndEmailsLast() { 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"));
service.placeOrder(1, 9, 2);
InOrder inOrder = inOrder(payments, orders, emails); inOrder.verify(payments).charge(1, new BigDecimal("998.00")); inOrder.verify(orders).save(any(Order.class)); inOrder.verify(emails).sendOrderConfirmation(1, 17, new BigDecimal("998.00"));}
// VerifyFailuresTest.java (part): the same check with the two lines swapped@Testvoid wrongOrder() { arrange(); service.placeOrder(1, 9, 2); InOrder inOrder = inOrder(payments, orders); inOrder.verify(orders).save(any(Order.class)); inOrder.verify(payments).charge(1, new BigDecimal("998.00"));}[ERROR] com.shoplite.lab.VerifyFailuresTest.wrongOrder -- Time elapsed: 0.005 s <<< FAILURE!
org.mockito.exceptions.verification.VerificationInOrderFailure:
Verification in order failure
Wanted but not invoked:
payments.charge(1, 998.00);
-> at com.shoplite.lab.VerifyFailuresTest.wrongOrder(VerifyFailuresTest.java:79)
Wanted anywhere AFTER following interaction:
orders.save(
Order[id=null, customerId=1, productId=9, quantity=2, total=998.00, paymentId=pay_501]
);
-> at com.shoplite.lab.OrderService.placeOrder(OrderService.java:32)What this code does
inOrder(payments, orders, emails)watches the three mocks together; eachinOrder.verifymust come after the one before it.- In
wrongOrderthe save is verified first, so Mockito looks forchargeafter the save and finds none: the real order was charge, then save.
Use it only where order is a rule. ShopLite must charge before saving the order (no unpaid orders) and send the email last (never mail about an order that failed). Most other tests should not care about order.
The last example does all of this by hand: recording doubles write every call into one shared list, and simple checks on that list play the part of verify, never(), the captor and InOrder.
Order of execution
Order the calls ShopLite must make
Tap the steps in the order they happen.
Example 6 · What verify, captors and InOrder do inside
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; }}
// ---------- recording doubles: what verify and captors do inside ----------
class CallLog { final List<String> calls = new ArrayList<>(); // every call, in order
long times(String method) { return calls.stream().filter(c -> c.startsWith(method + "(")).count(); }
int position(String method) { for (int i = 0; i < calls.size(); i++) { if (calls.get(i).startsWith(method + "(")) { return i; } } return -1; }}
class StockedProducts implements ProductRepository { private final CallLog log;
StockedProducts(CallLog log) { this.log = log; }
public Optional<Product> findById(int id) { log.calls.add("findById(" + id + ")"); return id == 9 ? Optional.of(new Product(9, "Clean Code", new BigDecimal("499.00"), 30)) : Optional.empty(); }
public void updateStock(int productId, int newStock) { log.calls.add("updateStock(" + productId + ", " + newStock + ")"); }}
class CapturingOrders implements OrderRepository { private final CallLog log; Order captured;
CapturingOrders(CallLog log) { this.log = log; }
public Order save(Order order) { log.calls.add("save(" + order + ")"); captured = order; return order.withId(17); }
public List<Order> findByCustomer(int customerId) { return List.of(); }}
public class RecordingVerifyDemo { public static void main(String[] args) { CallLog log = new CallLog(); CapturingOrders orders = new CapturingOrders(log); PaymentGateway payments = (customerId, amount) -> { log.calls.add("charge(" + customerId + ", " + amount + ")"); return "pay_501"; }; EmailSender emails = (customerId, orderId, total) -> log.calls.add("sendOrderConfirmation(" + customerId + ", " + orderId + ", " + total + ")"); OrderService service = new OrderService(new StockedProducts(log), orders, payments, emails);
service.placeOrder(1, 9, 2);
System.out.println("Calls, in order:"); log.calls.forEach(c -> System.out.println(" " + c)); System.out.println("times(1) charge? " + (log.times("charge") == 1)); System.out.println("never() updateStock? " + (log.times("updateStock") == 0)); System.out.println("captured order id: " + orders.captured.id()); System.out.println("captured order total: " + orders.captured.total()); System.out.println("charge before save? " + (log.position("charge") < log.position("save"))); System.out.println("save before email? " + (log.position("save") < log.position("sendOrderConfirmation"))); }}Calls, in order: findById(9) charge(1, 998.00) updateStock(9, 28) save(Order[id=null, customerId=1, productId=9, quantity=2, total=998.00, paymentId=pay_501]) sendOrderConfirmation(1, 17, 998.00) times(1) charge? true never() updateStock? false captured order id: null captured order total: 998.00 charge before save? true save before email? true
What this code does
- Every double adds a line to one shared
CallLog, so the list shows each call with its arguments, in order: that is what a Mockito mock records. times("charge") == 1playsverify,times("updateStock") == 0playsnever()(and showsfalse, because stock was updated),capturedplays the captor and the position checks playInOrder.
Next step
Check your understanding
12 quick questions