Understanding Mockito ArgumentCaptor using Spring Boot Test Example
Now there can be two scenarios-
-
1. The argument is passed externally to the method we are testing and then used by the collaborator during its own method call
method(argument arg) { collaborator.callMethod(arg); }
To test this method we mock the collaborator and then call the method as followsmethod(arg1); Mockito.verify(collaborator).callMethod(arg1);
So here in the test method we have the arg1 instance and hence can be verified -
2. The argument being used by the collaborator to make its own method call is not passed externally and but created inside the method being tested
method() { arg=CreateArgumentInternally(); collaborator.callMethod(arg); }
method();
But how do we verify the collaborator was called with which arguments since we don't have the access to the argument as it was created internally inside the method. This where the Mockito ArgumentCaptor comes into picture. Using the ArgumentCaptor we can get the argument instance created internally and used in the collaborator call and thus we can verify it.Mockito.verify(collaborator).callMethod(captor.capture()); Argument actual = captor.getValue();
The project structure is as follows-

package com.javainuse.service; import java.util.List; import com.javainuse.model.Employee; public interface EmployeeService { void insertEmployeeUsingEmployeeId(String employeeId); void insertEmployee(Employee emp); void insertEmployees(List<Employee> employees); void getAllEmployees(); void getEmployeeById(String empid); }The ServiceImpl class will be as follows-
package com.javainuse.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.javainuse.dao.EmployeeDao; import com.javainuse.model.Employee; import com.javainuse.service.EmployeeService; @Service public class EmployeeServiceImpl implements EmployeeService { @Autowired EmployeeDao employeeDao; @Override public void insertEmployee(Employee employee) { employeeDao.insertEmployee(employee); } @Override public void insertEmployeeUsingEmployeeId(String employeeId) { Employee emp = new Employee(); emp.setEmpId(employeeId); emp.setEmpName("testEmp"); employeeDao.insertEmployee(emp); } @Override public void insertEmployees(List<Employee> employees) { employeeDao.insertEmployees(employees); } public void getAllEmployees() { List<Employee> employees = employeeDao.getAllEmployees(); for (Employee employee : employees) { System.out.println(employee.toString()); } } @Override public void getEmployeeById(String empId) { Employee employee = employeeDao.getEmployeeById(empId); System.out.println(employee); } }