0Pricing
Java Academy · Lesson

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

  1. Parameterized Tests with @CsvSource and @MethodSource
  2. Mockito Advanced: Argument Captors and Spies
  3. Spring Boot Test Slices: @WebMvcTest and @DataJpaTest
  4. Testcontainers: Real Database Integration Tests
← Back to Java Academy