Invalid use of argument matchers! 1 matchers expected, 2 recorded:

Last modified date

Comments: 0

Contents

Problem

When using the Mockito Framework in my Spring Boot application, I kept on receiving this error from the test runner:

Invalid use of argument matchers! 1 matchers expected, 2 recorded

My testing mock looked like this:

when(userService.getDetails(ArgumentMatchers.anyString())).thenReturn(ArgumentMatchers.anyString());

Solution

The issue is caused when an Argument Matcher is returned in the thenReturn() function. Argument matchers aren’t allowed to be returned in this function.

Hence the error message makes sense because it was only expecting one Argument Matcher in the getDetails() function but it found a second Argument Matcher in thenReturn()which is what the error refers to.

Remove the argument matcher from thenReturn and instead return a value or object:

// PROBLEM
when(userService.getDetails(ArgumentMatchers.anyString())).thenReturn(ArgumentMatchers.anyString());

// SOLUTION
when(userService.getDetails(ArgumentMatchers.anyString())).thenReturn("test_user");

As you can see, I have replaced the second Argument Matcher with “test_user” String object and now it is able to successfully mock the function and run the test.

JakTech

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.