Table of contents
1.
Introduction
2.
Mockito ArgumentCaptor
3.
Methods of the ArgumentCaptor Class
4.
Mockito ArgumentCaptor Example
5.
FAQs
5.1.
What does ArgumentCaptor do in mockito?
5.2.
How does mockito mock work?
5.3.
Why do we need Mockito?
5.4.
Which annotation is used to create an ArgumentCaptor?
5.5.
Can mockito mock asynchronous classes?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Capturing Arguments in Mockito

Author Yukti Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this article, we will learn a common and important use case of Mockito ArgumentCaptor and its methods. 

To make the most out of this article, you should be familiar with the basics of the Mockitio Framework. Consider reading Getting Started With Mockito.

Mockito ArgumentCaptor

In the org.mockito package, there is a class called ArgumentCaptor, which captures arguments for mocked methods for further assertions. We can obtain the values passed when a particular method is invoked using an argument captor with the methods such as then() or verify(). In this way, we can provide additional JUnit assertions for our tests.

 

Note: It is always recommended to use ArgumentCaptor with verification but not with stubbing because, with stubbing, test readability decreases because captor is created outside of the assert block. Also, it may reduce defect localisation because if the stubbed method is not called, then no argument is captured.

Methods of the ArgumentCaptor Class

Some of the useful methods and their descriptions of the argument captor class are as follows:

  • T capture()
    It is used to capture the method arguments. This method must be used inside of verification.
    Returns:
    null or default values
     
  • ArgumentCaptor<U> forClass(Class<S>clazz)
    It builds a new argument captor.
    Type Parameters:
    S - Type of clazz
    U - Type of object captured by the newly built ArgumentCaptor
    Parameters:
    class - Type matching the parameter to be captured.
    Returns:
    A new ArgumentCaptor
     
  • List<T> getAllValues()
    It returns all the captured values if multiple arguments were captured. When the varargs method was called multiple times, this method returns a merged list of all values from all invocations.
    Returns: 
    captured argument value
     
  • T getValue()
    It returns all the captured values of the argument. If the verified method was called multiple times, then this method returns the latest captured value.
    Returns:
    captured argument value

Mockito ArgumentCaptor Example

Let’s say we define a class as shown in the below code:

class MathUtils {

    public int add(int x, int y) {
        return x + y;
    }


    public boolean isInteger(String s) {
        try {
            Integer.parseInt(s);
        } catch (NumberFormatException e) {
            return false;
        }
        return true;
    }

    public long squareLong(long l) {
        return l * l;
    }
}

Then using ArgumentCaptor, the tests for the above code can be written as follows:

@Test
void test() {
    MathUtils mockMathUtils = mock(MathUtils.class);
    when(mockMathUtils.add(1, 1)).thenReturn(2);
    when(mockMathUtils.isInteger(anyString())).thenReturn(true);


    ArgumentCaptor acInteger = ArgumentCaptor.forClass(Integer.class);
    ArgumentCaptor acString = ArgumentCaptor.forClass(String.class);


    assertEquals(2, mockMathUtils.add(1, 1));
    assertTrue(mockMathUtils.isInteger("1"));
    assertTrue(mockMathUtils.isInteger("999"));


    verify(mockMathUtils).add(acInteger.capture(), acInteger.capture());
    List allValues = acInteger.getAllValues();
    assertEquals(List.of(1, 1), allValues);

    verify(mockMathUtils, times(2)).isInteger(acString.capture());
    List allStringValues = acString.getAllValues();
    assertEquals(List.of("1", "999"), allStringValues);
}

FAQs

What does ArgumentCaptor do in mockito?

ArgumentCaptor allows us to capture an argument passed to a method in order to inspect it. This is especially useful when we can't access the argument outside of the method we'd like to test.

How does mockito mock work?

With Mockito, you create a mock, tell Mockito what to do when specific methods are called on it, and then use the mock instance in your test instead of the real thing.

Why do we need Mockito?

Mockito framework is used to simplify the development of a test by mocking external dependencies and use them in the test code.

Which annotation is used to create an ArgumentCaptor?

The @Captor annotation is used to create an ArgumentCaptor instance which is used to capture method argument values for further assertions.

Can mockito mock asynchronous classes?

Mockito can mock asynchronous classes.

 

Must Recommended Topic - Difference between argument and parameter

Conclusion

In this article, we have extensively discussed Mockito ArgumentCaptor.

We hope that this blog has helped you enhance your knowledge regarding Mockito ArgumentCaptor and if you would like to learn more, check out our articles on 

Mockito AnnotationsCreating Mocks and need of mockingTesting exceptions

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. 

Enrol in our courses and refer to the mock test and problems available.

Take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow. 

Happy Coding!

Live masterclass