Creating Custom Argument Matchers

To create your own matcher, the ArgumentMatchers class has a method called argThat, which takes an ArgumentMatcher (singular) as an argument. ArgumentMatcher is an interface containing a single abstract method, with this signature:

 boolean matches(T argument)

This method should return true if the argument matches whatever condition you implement, and false otherwise.

In the dark days before lambda expressions were added in Java 8, implementing your own matcher wasn’t exactly difficult, but it was verbose. The example given in the documentation is hardly inspiring (comments added):

 // custom matcher that implements the ArgumentMatcher interface
 class​ ListOfTwoElements ​implements

Get Mockito Made Clear now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.