Using Matches for null parameter with Mockito

I was using Mockito to write a unit test today and had a brief struggle trying to write a Matcher for a parameter I expected to be null.

Here is the method in my interface that was causing problems:

public interface ItemService
    List<Item> findItems(String query, Map<String, String> qualifiers);

In my unit test I started with writing this for argument verification since I expected the second parameter for the Map to be null:

 verify(itemService).findItems(anyString(), null);

This resulted in the following error when running the unit test:

Invalid use of argument matchers!
2 matchers expected, 1 recorded:
-> at com.stevewall123.ItemServiceTest.testFindITems(

The error is pretty straight-forward.  Once you use a Matcher on one argument then they need to be used on all arguments.  To fix the error, I needed to use the Matchers class isNull() method.  This method will verify the argument is null.  So in my unit test, I changed the argument verification line to:

 verify(itemService).findItems(anyString(), isNull(Map.class);

And now the test passes!

About stevewall123

I am a Lead Software Engineer in Minneapolis working for Thomson Reuters. I am currently working on projects using Java, JavaScript, Spring, Elasticsearch, Hazelcast, Liquibase and Tomcat. Previously, I used C#, GWT, Grails, Groovy, JMS and JBoss Drools Guvnor. In the past I have worked on projects using J2EE, Swing, Webwork, Hibernate, Spring, Spring-WS, JMS, JUnit and Ant.
This entry was posted in Java, Mockito and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s