Argument matchers are mainly used for performing flexible verification and stubbing in Mockito. It extends ArgumentMatchers class to access all the matcher functions. Mockito uses equal() as a legacy method for verification and matching of argument values. In some cases, we need more flexibility during the verification of argument values, so we should use argument matchers instead of equal() method. The ArgumentMatchers class is available in org.mockito package.
The ArgumentMatchers class contains a variety of methods; some of them are listed below:
Note: All the arguments must be provided by the matchers while using argument matchers.
Example of Argument Matcher
Here, we are going to create an example of Argument matchers. We are using the anyInt() method in our test case, we can use any of the methods available in the ArgumentMatchers class.
The following output shows that the test is successfully running using argument matchers.
Example of throwing an exception using Argument matcher
Here, we are going to create an example of throwing an exception using argument matchers. In this example, we will use JUnit feature @Test(expected = RuntimeException.class) to prevent the test failure. If we don't use it, the test fails and throws an exception.
The following output shows that the test is successfully running using the @Test(expected = RuntimeException.class).
The following output shows an error because we haven't used the @Test(expected = RuntimeException.class).