Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Show how to use an ArgumentCaptor to check the email address passed to emailSender.send(Email email) inside a service under test.

We create an ArgumentCaptor<Email>, either with ArgumentCaptor.forClass(Email.class) or with a @Captor field, run the service, and then call verify(emailSender).send(captor.capture()). The captor now holds the Email the service built, so we can assert on captor.getValue().to(), and getAllValues() gives every captured Email when send() was called more than once.

Why this question is asked

Many services build an object internally and hand it to a collaborator: a registration service builds a welcome Email and passes it to an EmailSender. The test cannot see that object, because the service never returns it. Interviewers ask about ArgumentCaptor because it is the standard Mockito tool for exactly this situation, and because how we use it shows whether we know the difference between checking what happened and setting up what should happen. In this answer, we will recap the test setup, write the captor test step by step, see how to handle several calls, and then look at where captors belong and where they do not.

1A Quick Recap of the Code Under Test

Let us start with a small service. When a user registers, RegistrationService saves the user and sends a welcome email through an EmailSender. EmailSender is an interface, so in a unit test we replace it with a mock: a fake object that Mockito creates, which records every call made to it and returns default values such as null or 0 unless we tell it otherwise.

The Email object is created inside register(). Our test never gets a reference to it, so we cannot simply compare it with an expected value we hold. We need a way to grab the argument that reached the mock. That is the job of an argument captor, an object that remembers the argument passed to a method during verification.

Java
public record Email(String to, String subject, String body) {}
public interface EmailSender {
void send(Email email);
}
public class RegistrationService {
private final EmailSender emailSender;
public RegistrationService(EmailSender emailSender) { this.emailSender = emailSender; }
public void register(String address) {
// ... save the user ...
emailSender.send(new Email(address, "Welcome", "Hello and welcome!"));
}
}

Notice that Email is a record, so its accessor for the address is to(), not getTo(). The test will use that accessor once it has captured the object.

2Writing the Test With a Captor

The test has three parts. First we arrange: create the mock and the service. Then we act: call register(). Finally we assert: verify that send() was called and capture the Email it received.

Java
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*;
class RegistrationServiceTest {
EmailSender emailSender = mock(EmailSender.class);
RegistrationService service = new RegistrationService(emailSender);
@Test
void sendsWelcomeEmailToTheNewUser() {
ArgumentCaptor<Email> captor = ArgumentCaptor.forClass(Email.class);
service.register("a@b.com");
verify(emailSender).send(captor.capture()); // passes: send() was called once
Email sent = captor.getValue();
assertEquals("a@b.com", sent.to()); // passes
assertEquals("Welcome", sent.subject()); // passes
}
}
Step throughHow the captor gets the Email
TestRegistrationServiceEmailSender mockCaptor
register("a@b.com")
send(new Email(...)), recorded
verify(...).send(captor.capture())
matching call found, store its Email
getValue().to()
"a@b.com"

6 messages in order. Play them, or step through them one at a time.

The mock records the call first; the captor fills only during verification.

Notice the order. The captor is used after the service has run. When Mockito executes verify(emailSender).send(captor.capture()), it looks at the calls the mock recorded, checks that send() was called exactly once (times(1) is the default), and while matching, it stores the Email argument in the captor. Only then does getValue() have something to return.

The reason captor.capture() sits inside verify() is that capture() is itself an argument matcher. It matches any Email and remembers it. If we called getValue() without a verify() before it, Mockito would complain that no argument value was captured.

3Using @Captor Instead of forClass()

ArgumentCaptor.forClass(Email.class) works well for a simple type. For a generic type, such as a List<Email>, forClass() can only take the raw List.class, and we get an unchecked conversion warning. The @Captor annotation solves this, because Mockito reads the full generic type from the field declaration. It needs the Mockito JUnit 5 extension to create the field before each test.

Java
@ExtendWith(MockitoExtension.class)
class RegistrationServiceTest {
@Mock EmailSender emailSender;
@Captor ArgumentCaptor<Email> captor; // created by the extension
@Captor ArgumentCaptor<List<Email>> batch; // no unchecked cast needed
@Test
void sendsWelcomeEmail() {
new RegistrationService(emailSender).register("a@b.com");
verify(emailSender).send(captor.capture());
assertEquals("a@b.com", captor.getValue().to()); // passes
}
}

Both styles do the same thing. Most teams pick @Captor when they already use the extension, and forClass() in tests that create their mocks by hand.

4Capturing Several Calls With getAllValues()

Sometimes the code under test calls the collaborator more than once. Suppose an invite() method sends one email per address. getValue() would only return the last captured value, so we use getAllValues(), which returns them all in call order.

Java
service.invite(List.of("a@b.com", "c@d.com"));
verify(emailSender, times(2)).send(captor.capture());
List<String> addresses = captor.getAllValues().stream().map(Email::to).toList();
assertEquals(List.of("a@b.com", "c@d.com"), addresses); // passes
assertEquals("c@d.com", captor.getValue().to()); // the last one

Notice that we changed the verification to times(2). Without it, verify() would fail because it expects exactly one call by default, so the captor and the count check work together.

5Captors Are for Verification, Not for Stubbing

There is one rule that keeps captor tests honest: use them in verify(), not in when(). It is technically possible to write when(emailSender.validate(captor.capture())).thenReturn(true), but that is a poor test. The stub would match any argument, so it says nothing about what the service should pass, and the captured value is only checked later, far from the stub, which makes failures confusing.

If the stubbed behaviour depends on the argument, we write that dependency directly with eq() or argThat() in the when() call. If we want to check what was passed, we do it in verify() with a captor. Keeping the two roles separate means the setup describes the world and the verification describes the result.

6Follow-up questions

What happens if send() was never called?

verify(emailSender).send(captor.capture()) fails with a WantedButNotInvoked error, which tells us the method was expected but the mock recorded no such call. We never reach getValue(), so the failure message points straight at the real problem.

Why not just override equals() and verify with the expected Email?

That is often better when the whole object is predictable. Because Email is a record, verify(emailSender).send(new Email("a@b.com", "Welcome", "Hello and welcome!")) works and is shorter. A captor helps when only some fields matter, or when a field is unpredictable, such as a generated token or a timestamp.

Does the captor keep values between tests?

No, as long as each test gets a fresh captor. With a @Captor field and MockitoExtension, a new captor is created before every test, and a local forClass() captor lives only inside its test method.

7Conclusion

In this answer, we saw how to check an object that a service builds internally and passes to a mock. We created an ArgumentCaptor with forClass() or @Captor, ran the service, verified send() with captor.capture(), and asserted on getValue().to(). For repeated calls we combined times(n) with getAllValues(). Finally, we kept captors in verification, where they belong, and left stubbing to eq() and argThat().

What to say in the interviewAbout 60 seconds aloud

Open with

When the service builds the Email internally I cannot compare it with a value I hold, so I capture it. I declare an ArgumentCaptor of Email, either with ArgumentCaptor.forClass(Email.class) or with a @Captor field under MockitoExtension, which also handles generic types without an unchecked cast.

Then, if they want more

I call the service first, then verify(emailSender).send(captor.capture()). The capture call is a matcher, so during verification Mockito checks that send was called once and stores the argument. Then I assert, for example assertEquals("a@b.com", captor.getValue().to()).

If the code sends several emails, I verify with times of the right count and read getAllValues(), which returns them in call order, while getValue() would return only the last one. I use captors only in verify, not in when, because a capturing stub matches anything and hides what the code should pass.

And if the whole object is predictable and has a proper equals, like a record, I would just verify with the expected Email directly, which is even simpler.

About this answer

Last updated
12 November 2026
Versions it names
JUnit 5
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Show how to use an ArgumentCaptor to check the email address passed to...": https://scrivio-interview-library.netlify.app/java/mocking/9b186fee20/