Table of contents
1.
Introduction
2.
Methods in Argument Matcher class
3.
Example of Argument matcher
3.1.
BookServiceTest
3.2.
Output
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024

Argument Matcher

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

Introduction

The article will stress the usage of argument matcher, method type and method name, and a brief description. Argument matchers are mostly utilised in Mockito to conduct flexible verification and stubbing. To access all of the matcher methods, it extends the ArgumentMatchers class. Equal() is a heritage method that Mockito uses to verify and match parameter values. In some circumstances, additional flexibility is required during the verification of argument values, hence argument matchers should be used instead of the equal() function. The org.mockito package contains the ArgumentMatchers class.

Methods in Argument Matcher class

There are several methods in the ArgumentMatchers class, some of which are given below:

Method type & Method name

Description

<T> any()

It matches null values and varargs as well as all other values (everything).

boolean anyBoolean()

Any boolean or not-null boolean value matches it.

byte anyByte()

Any byte or not-null byte value matches it.

char anyChar()

Any char or not-null character value is matched.

Collection <T> anyCollection

It matches any collection that isn't null in the application.

double anyDouble()

Any double or not-null double value matches it.

float anyFloat()

It matches to any float or not-null float values.

int anyInt()

It matches any integer value that is an int or a not-null value.

Iterable<T> anyIterable()

It matches any iterable values that aren't null.

List<T> anyList()

It is equivalent to any not-null list.

long anyLong()

It is compatible with any long or not-null long value.

Set<T> anySet()

It is compatible with any not-null set.

short anyShort()

It may be used to match any short or not-null short value.

String anyString()

It matches any String that isn't null.

<T>argThat(ArgumentMatcher<T>matcher)

It allows you to make your own argument matchers.

boolean booleanThat(ArgumentMatcher<Boolean> matcher)

It allows you to make your own boolean argument matchers.

byte byteThat(ArgumentMatcher<Byte> matcher)

It allows you to make your own byte argument matchers.

char charThat(ArgumentMatcher<Character> matcher)

It allows you to make your own char argument matchers.

String contains(String substring)

It corresponds to the substring in the String argument.

double doubleThat(ArgumentMatcher<Double> matcher)

It allows you to make your own double argument matchers.

String endsWith(String suffix)

It corresponds to the String input that ends with the suffix specified.

boolean eq(boolean value)

It corresponds to the boolean argument that has the same value as the provided value.

double eq(double value)

It corresponds to the double argument, which has the same value as the provided value.

long eq(long value)

It corresponds to the long argument that has the same value as the provided value.

<T> isNotNull()

It is equivalent to the not null argument.

<T> is Null()

It matches the null argument.

<T> same(T value)

It's the same as the null argument.

Example of Argument matcher

We'll make an example of Argument Matchers right now. We're using the anyInt(), anyBoolean function in our test example, although we could use any of the ArgumentMatchers class's methods.

BookServiceTest

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.*;
import org.mockito.junit.jupiter.MockitoExtension;



import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;


import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*;


@ExtendWith(MockitoExtension.class)
class BookServiceTest {
   @InjectMocks
   private BookService bookService;


   @Mock
   private BookRepository bookRepository;


   @Test
   public void testUpdatePrice() {
       Book book1 = new Book("ISBN5321", "Mockito Test", 600, LocalDate.now());
       Book book2 = new Book("ISBN5321", "Mockito Test", 500, LocalDate.now());
       when(bookRepository.findBookById(any(String.class))).thenReturn(book1);
       bookService.updatePrice("ISBN5321", 500);
       verify(bookRepository).save(book2);
   }


   @Test
   public void testSpecificTypeOfArgumentMatchers() {
       Book book = new Book("ISBN5321", "Mockito Test", 600, LocalDate.now());
       when(bookRepository.findBookByTitleAndPriceAndIsDigital(anyString(), anyInt(), anyBoolean())).thenReturn(book);
       Book actualBook = bookService.getBookByTitleAndPriceAndIsDigital("Mockito Test", 600, true);
       assertEquals("Mockito Test", actualBook.getTitle());
   }


   @Test
   public void testCollectionTypeArgumentMatchers() {
       List<Book> books = new ArrayList<>();
       Book book = new Book("ISBN5321", "Mockito Test", 600, LocalDate.now());
       books.add(book);
       bookService.addBooks(books);
       verify(bookRepository).saveAll(anyList()); // anySet, anyMap, anyCollection
   }


   @Test
   public void testStringTypeArgumentMatchers() {
       Book book = new Book("ISBN5321", "Mockito Test", 600, LocalDate.now());
       when(bookRepository.findBookByTitleAndPriceAndIsDigital(contains("Action"), anyInt(), anyBoolean())).thenReturn(book);
       Book actualBook = bookService.getBookByTitleAndPriceAndIsDigital("JUnit 5 In Action", 600, true);
       assertEquals("Mockito Test", actualBook.getTitle());
   }
}
You can also try this code with Online Java Compiler
Run Code

Output

FAQs

1. What is an argument matcher?
Ans: Argument matchers are mostly utilised in Mockito to conduct flexible verification and stubbing. To access all of the matcher methods, it extends the ArgumentMatchers class. Equal() is a heritage method that Mockito uses to verify and match parameter values.


2. What is ArgumentCaptor used for?
Ans: ArgumentCaptor lets us investigate an argument supplied to a method by capturing it. This comes in handy when we can't get to the argument outside of the method we're testing.


3. Can the Mockito Matcher methods be used as return values?
Ans: Matcher methods can't be used as return values in Mockito; for example, there's no way to say thenReturn(anyInt()) or thenReturn(any(Foo. class)). Mockito has to know which instance to return in stubbing calls, and it will not select a random return value for you.


4. What are matchers in JUnit?
Ans: Matchers is a third-party component of the JUnit framework. Hamcrest, a framework, was responsible for the addition of matchers. You don't have to download and install Hamcrest because JUnit 4.8. 2 includes it by default.

 

Read Also -  Difference between argument and parameter

Key Takeaways

In this blog, we have looked into the implementation of argument matchers. There implementation, however, it is recommended to go through the official documentation to learn more and advised to do hands-on practise to get a clear understanding of the article.


We hope that this blog has helped you enhance your knowledge, if you would like to learn more, check out our articles on Mocha Installation and Getting StartedMocha Assertions. Do upvote our blog to help other ninjas grow. 

 

Happy Coding!

Live masterclass