Mockito Advanced: Argument Captors and Spies
Capture method arguments with ArgumentCaptor and partially mock real objects with Mockito.spy.
ArgumentCaptor: Capturing Method Arguments
ArgumentCaptor captures the arguments passed to a mocked method so you can assert on them. Useful when the argument is built inside the system under test and you cannot access it directly.
Creating and Using ArgumentCaptor
Create a captor for the argument type, pass captor.capture() as the argument matcher in verify(), then call captor.getValue() to get the captured argument.
@Test
void sends_correct_email() {
ArgumentCaptor<EmailMessage> captor = ArgumentCaptor.forClass(EmailMessage.class);
userService.register(new CreateUserRequest("alice@example.com"));
verify(emailService).send(captor.capture());
EmailMessage msg = captor.getValue();
assertEquals("alice@example.com", msg.getTo());
assertTrue(msg.getSubject().contains("Welcome"));
}All lessons in this course
- Parameterized Tests with @CsvSource and @MethodSource
- Mockito Advanced: Argument Captors and Spies
- Spring Boot Test Slices: @WebMvcTest and @DataJpaTest
- Testcontainers: Real Database Integration Tests