javaspringmockingmockitomatcher

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Invalid use of argument matchers


I have multiple mock statements in my test class and everything works fine. I am adding a new statement for a DAO mocking as :

 Mockito.when(myDAO.saveOrUpdate(Mockito.any())).thenReturn(Mockito.any());

But I get exception as :

org.mockito.exceptions.misusing.InvalidUseOfMatchersException:  Invalid use of argument matchers!

I have used argument matchers and not raw values so I have not mixed anything.What can be the cause here?


Solution

  • You called an argument matcher outside a call to when or verify, which is illegal.

    See Argument matchers:

    Matcher methods like any(), eq() do not return matchers. Internally, they record a matcher on a stack and return a dummy value (usually null). This implementation is due to static type safety imposed by the java compiler. The consequence is that you cannot use any(), eq() methods outside of verified/stubbed method.

    See also How do Mockito matchers work?