Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 37 · Argument Matchers and Captors

ArgumentCaptor – Capture and Inspect Arguments

Use Mockito ArgumentCaptor to grab the arguments passed to a mock, assert on their fields, collect values from several calls, and capture callbacks.

Sometimes verify(repo).save(someUser) is not possible, because the object passed to save is created inside the code under test: a new User, an Order with a generated id, an email message assembled from several parts. You cannot write the expected object in the test, or you could but comparing it as a whole with equals would give an unhelpful "arguments are different" message. An ArgumentCaptor solves this: it records the actual argument during verification and hands it to you, so you can assert on its fields one by one with ordinary assertions.

Real Mockito code is read-only. The runnable examples use the Mini stand-in from What Is Mockito?, which has ArgumentCaptor.forClass, capture(), getValue() and getAllValues() with the same shape as Mockito. The annotation @Captor is shown as real code only.

The three steps

Java
import org.mockito.ArgumentCaptor;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;

// 1. create the captor for the argument's type
ArgumentCaptor<User> captor = ArgumentCaptor.forClass(User.class);

// 2. use captor.capture() as the argument inside verify(...)
verify(users).save(captor.capture());

// 3. read what was captured and assert on it
User saved = captor.getValue();
assertEquals("[email protected]", saved.email());
assertTrue(saved.active());

captor.capture() is a matcher: it matches any argument and records it, so the matcher rules apply. If the call has two arguments, the second must also be a matcher, for example verify(mailer).send(eq("[email protected]"), textCaptor.capture()). Captors record during verification, which is the intended use. Capturing inside when(...) stubbing is possible but discouraged: it records the calls made later by the code under test in unclear ways, and the Mockito documentation recommends against it.

getValue() returns the last captured argument, getAllValues() returns a list of all captured arguments in call order.

Try it: inspecting an object created by the code under test

Java Capturing a User created inside the service

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Compare with verify(users).save(new User("[email protected]", "Ana", true)): that also works here because a record has equals, but when it fails you only learn that "the arguments are different". With the captor, each property has its own check and message, and you can ignore properties that are irrelevant (such as a generated id or timestamp).

Several calls: getAllValues

When the code makes several calls, a captor collects all of the arguments in order. Use times(n) so that Mockito knows how many calls to expect:

Java Collecting arguments of several calls

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Both captors were used in the same verify, so their lists line up: to.getAllValues().get(1) belongs with text.getAllValues().get(1).

Capturing callbacks

A very practical use is capturing a callback the code under test hands to a collaborator, and then calling it yourself to simulate the collaborator finishing. This turns asynchronous-looking code into a plain, deterministic test:

Java Capture a callback and trigger it

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

@Captor and generic types

With the JUnit extension you can declare captors as fields:

Java
@ExtendWith(MockitoExtension.class)
class ReminderTest {
    @Mock Mailer mailer;
    @Captor ArgumentCaptor<String> textCaptor;
    @Captor ArgumentCaptor<List<String>> batchCaptor;     // generics work here
}

ArgumentCaptor.forClass(List.class) cannot express List<String> (class literals have no generic parameters), so you would need an unchecked cast. @Captor reads the generic type from the field and avoids that.

Things to watch

  • The captured object is the real object, not a copy. If the code under test (or your test) mutates it afterwards, getValue() shows the mutated state. For mutable arguments, assert before changing anything.
  • getValue() with no captured value fails with a clear error. Make sure the verify really ran and matched.
  • Do not overuse captors. If one eq(...) or argThat(...) expresses the check, use that; a captor plus five assertions is for rich objects.
  • A captor still counts as verification. verify(users).save(captor.capture()) also checks the call count (times(1) by default), which can surprise you when the method was called twice.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. When is an ArgumentCaptor most useful?

    A captor lets you inspect objects the test cannot easily construct in advance, with clear, field-by-field assertions.
  2. 2. Where do you pass captor.capture()?

    capture() is a matcher used in the verified call. It records the argument for each matching call.
  3. 3. What does getValue() return when the method was called three times?

    getValue() returns the last captured value; getAllValues() returns all of them in call order.
  4. 4. Why use @Captor with a generic type like List<String>?

    A class literal has no generic parameters. @Captor reads the field's generic type and avoids an unchecked cast.

Summary

  • ArgumentCaptor.forClass(T.class), verify(mock).method(captor.capture()), then captor.getValue() or getAllValues().
  • Captors inspect arguments created inside the code under test; assert with ordinary assertions for clear messages.
  • Using a captor in verify also checks the call count; use times(n) for several calls.
  • Capture callbacks to simulate asynchronous completion deterministically.
  • Use @Captor for generic argument types, and remember that captured objects are references, not copies.

Next: Spies Basics