Search code examples
javajunitmockitomatcher

org.mockito.exceptions.misusing.InvalidUseOfMatchersException:


My method in the service and test class :

public void updateSubModuleOrder(Long[] data, Long moduleSysId, Long userId) {
    try {
        for (int i = 0; i < data.length; i++) {
            SubModule subModule=new SubModule();

            int temp = i + 1;
            userSubmodule.setDsplySeq(temp);
            userSubModuleDao.saveOrUpdate(userSubmodule);
@Test
public void testupdateSubModuleOrder(){
    UserModuleServiceImpl userModuleServiceImpl = new UserModuleServiceImpl();
    UserSubModuleDao userSubModuleDao = mock(User//set the required param ,some code here//
    UserSubModuleId userSubModuleId=new UserSubModuleId();
    //some code//
    when(userSubModuleDao.findById((any(UserSubModuleId.class)),false)).thenReturn(userSubModule);
    when(userSubModuleDao.saveOrUpdate(any(UserSubModule.class))).thenReturn(null);
    userModuleServiceImpl.updateSubModuleOrder(data, moduleSysId, userId);

};*

the error I get is

FAILED: testupdateSubModuleOrder
org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
2 matchers expected, 1 recorded:
-> at com.TestUserModuleServiceImpl.testupdateSubModuleOrder(TestUserModuleServiceImpl.java:267)

This exception may occur if matchers are combined with raw values:

//incorrect:
someMethod(anyObject(), "raw String");

When using matchers, all arguments have to be provided by matchers. For example:

//correct:
someMethod(anyObject(), eq("String by matcher"));

the method findbyID is a baseDao method which my dao extends . It is not a final or static but still I'm getting this problem.


Solution

  • You either have to specify no matchers, or all the arguments need matches. So this:

    when(userSubModuleDao.findById((any(UserSubModuleId.class)),false))
    

    should be:

    when(userSubModuleDao.findById(any(UserSubModuleId.class), eq(false)))
    

    (I've removed the redundant brackets from around the any call.)

    From the Matchers documentation:

    Warning:

    If you are using argument matchers, all arguments have to be provided by matchers.