ArgumentCaptor is a class provided by Mockito and used to verify the arguments passed to a mock method. It should be used for verification and not for stubbing.
Normally with matchers you can only verify that a method has been called with a particular object type or a specific object. ArgumentCaptor is more flexible and allows you to check each specific member of the object passed.
Here's a short example:
ArgumentCaptor<Student> arg = ArgumentCaptor.forClass(Student.class); verify(mock).execute(arg.capture()); assertEquals("Ale", arg.getValue().getName());
Let's now analize a booking system:
import java.util.Date; /** * Contains all the information of an appointment */ public class Appointment { private Date date; private String event; public Appointment(Date date, String event) { this.date = date; this.event = event; } public Date getDate() { return date; } public String getEvent() { return event; } } import java.util.ArrayList; import java.util.List; /** * Calendar used to set appointments */ public class Calendar { private List<Appointment> appointments = new ArrayList<>(); public void addAppointment(Appointment appointment) { appointments.add(appointment); } // Other methods } import java.util.Date; /** * Manage appointments on a calendar */ public class BookingSystem { private Calendar calendar; public BookingSystem(Calendar calendar) { this.calendar = calendar; } public void book(Date date, String event) { Appointment appointment = new Appointment(date, event); calendar.addAppointment(appointment); } }
Here's the test, using ArgumentCaptor:
import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.runners.MockitoJUnitRunner; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import java.util.Date; import static org.junit.Assert.assertEquals; /** * Test to demonstrate the use of ArgumentCaptor */ @RunWith(MockitoJUnitRunner.class) public class BookingSystemTest { @Test public void myTest() { Calendar calendar = mock(Calendar.class); BookingSystem bookingSystem = new BookingSystem(calendar); // Initialize the ArgumentCaptor ArgumentCaptor<Appointment> argCaptor = ArgumentCaptor.forClass(Appointment.class); // Initialize date and event Date currentDate = new Date(); String event = "Do this test!"; // Add the appointment to the system bookingSystem.book(currentDate, event); // Verify that the appointment has been added verify(calendar).addAppointment(argCaptor.capture()); // Verify that it has been added with the correct values assertEquals(currentDate, argCaptor.getValue().getDate()); assertEquals(event, argCaptor.getValue().getEvent()); } }
As you can see, I can now make sure that date and event are as expected.
Copyright © 2013 Welcome to the website of Davis Fiore. All Rights Reserved.