Introduction
Mockito is an open-source framework used for testing in Java. The Mockito framework allows the creation of automated unit tests and mock tests for behavior-driven development(BDD) or test-driven development(TDD).
Argument Matchers are primarily used for stubbing and performance flexible verification in Mockito. We can access the Argument Matcher class using the org.mockito package.
To access the org.mockito package, we need to add the following dependencies,
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.21.0</version>
<scope>test</scope>
</dependency>
Let us look at an example of Argument Matchers,
when(codingNinjas.analyze(anyString())).thenReturn("Hey Ninja");In the above example, we return “Hey Ninja” whenever any string is passed to the compiler.
Custom Argument Matcher
Sometimes the regular Argument Matchers are not enough, and the developer needs custom-created matchers for the best possible approach with the highest quality tests. Custom Argument Matchers can prove to be a more clean and maintainable approach for testing.
Let us look at an example of Custom Argument Matchers,
public class customMatcher implements ArgumentMatcher<Message> {
private Message left;
@Override
public boolean matche(Message right) {
return left.getFrom().equals(right.getFrom()) &&
left.getText().equals(right.getText()) &&
left.getTo().equals(right.getTo()) &&
right.getId() != null;
right.getDate() != null &&
}
}
The test for the above Java code will look something like this,
verify(messageService, times(1)).deliverMessage(argThat(new customMatcher(message)));




