@Captor Annotation in Mockito with Example

By | October 15, 2020

In this post, We will talk and learn about @Captor Annotation in Mockito with Example

Mockito ArgumentCaptor and @Captor Annotation

Usually, Mockito’s ArgumentCaptor is used to capture arguments for mocked methods. ArgumentCaptor is used with Mockito to verify() methods to get the arguments passed when any method is called. This way usually, we can use additional JUnit assertions for our test cases.

Mockito ArgumentCaptor

We can usually create ArgumentCaptor an instance for any given class, then we use its capture() method to  use with verify() methods.

Finally, we can get arguments from getValue() and getAllValues() methods.

getValue() the method can be used when we have captured a single argument. If the verified method was called multiple times then getValue() the method will return the latest captured value.

If you have multiple arguments to capture then you have to call getAllValues() to get the list of arguments.

Mockito ArgumentCaptor Example

Mockito @Captor

We can use @Captor Mockito annotation to create argument captor at field level. So instead of initializing field level ArgumentCaptor as:

ArgumentCaptor<String> argumentCaptor = ArgumentCaptor.forClass(String.class);

We can use @Captor as:

@Captor
private ArgumentCaptor<String> argumentCaptor;

Note that we have to call MockitoAnnotations.initMocks(this); before test methods to get it initialized by the Mockito framework.

Mockito @Captor Example

pom.xml

Person.java

 

MockitoCaptorTest1.java

 

MockitoCaptorTest2.java

 

MockitoCaptorTest3.java 

Now right-click on the Project and select Run As then JUnit Test as shown in the below Image.

The Output of the above project:

Some Key Points:

  • We may use to create org.mockito.ArgumentCaptor<T> instance for any class then its capture() method is used with verify() methods.
  • We can  capture arguments from getValue() and getAllValues() methods.
  • ArgumentCaptor getValue() method can be used when we have captured a single argument. If the verify method was called multiple times then getValue() method will return the latest captured value only.
  • If multiple arguments are captured then we may call getAllValues() to get the list of arguments.

You May Also Like:

What is Mocking?
Why Need for mocking?
What are the Benefits of Mockito?
How to mock interface using Mockito example?
Mockito and JUnit Integration Using Maven Example
@Mock and @Spy Mockito Annotations With Example
@InjectMocks Annotation in Mockito with Example
Mockito – Verifying Method Calls
Adding behavior to mocked object in Mockito
Mocking Void Methods with Mockito
Mocking Exception Throwing using Mockito
Mockito’s mock Overloaded Methods

That’s all about @Captor Annotation in Mockito with Example?
If you have any feedback or suggestion please feel free to drop in below comment box.

Leave a Reply

Your email address will not be published. Required fields are marked *