Video in progress

Strong Junior 🧪 Testing

When do you need ArgumentCaptor, and what can you use instead?

ArgumentCaptor catches an argument passed to a mock so you can inspect its contents in detail, especially when the object is created inside the method. For simple cases argThat or eq is enough.

📖 Answer

Say the service creates an AuditEvent inside and calls auditLog.write(event). In the test you have no reference to this object, because it was born inside the method.

@Captor ArgumentCaptor<AuditEvent> eventCaptor;

@Test
void bekor_qilish_auditga_yoziladi() {
    service.cancel(42L, "admin");

    verify(auditLog).write(eventCaptor.capture());
    AuditEvent event = eventCaptor.getValue();
    assertEquals("ORDER_CANCELLED", event.type());
    assertEquals("admin", event.actor());
}

If the method was called several times, getAllValues() returns all of them as a list.

When you don't need it:

  • don't use a captor in stubbing (when(...)), it's meant for verify;
  • if you're checking a single condition, verify(auditLog).write(argThat(e -> e.actor().equals("admin"))) is shorter;
  • if the argument is a record that implements equals properly, a plain verify(auditLog).write(expectedEvent) is the cleanest option.

If captors pile up, it can be a sign that the test is watching the code too closely from the inside.