ArgumentCaptor
The AgrumentCaptor is a class that is defined in the org.mockito package. It is used to capture argument values for further assertions. We use argument captor with the methods like verify() or then() to get the values passed when a specific method is invoked.
There are some important methods of the ArgumentCaptor class that are given below:
Method type and method name | Description |
---|---|
T capture() | It is used to capture the method arguments. |
ArgumentCaptor<U> forClass(Class<S>clazz) | It is used to build a new ArgumentCaptor. |
List<T> getAllValues() | It is used to return all the captured values. |
T getValue() | It is used to return all the captured values of the argument. |
It is suggested to use ArgumentCaptor with verification but not with stubbing. Because with stubbing, it reduces the test readability as captor is defined outside the assert (verify or then) block.
Example of ArgumentCaptor
Here, we are going to create an example of ArgumentCapture using the BDD style. In this example, we are using the then().should() method instead of using the verify() method that is available in the BDDMockito class. The main aim of using them is to make the code more readable and understandable.
Step 1: Create an interface named ToDoService that contains two unimplemented methods.
ToDoService.java
Step 2: Create the implementation class of the ToDoService interface named ToDoBusiness.
ToDoBusiness.java
Step 3: Create a mock class named ToDoBusinessMock for testing purposes. Here, we have declared an ArgumentCaptor that captures the argument of this (todoService) mock when deleteTodos() method is called.
ToDoBusinessMock.java
In the above code, we have captured the argument and checked whether the argument passed is “Use Spring MVC” or not, by using the getValue() method.
Output
Consider a scenario in which we want to delete multiple values at the same time. In these kinds of cases, the method named getAllValues() is used, as shown below.
But the above code will throw an exception, as shown below.
To remove the above exception, we need to specify the number of times the method should be invoked. Let’s suppose there are two non-Hibernate items available in the list, so we need to invoke the method two times, as shown below.
Output