0

I want to test this method :

public void some_method(SomeFactory someFactory) {
        A a = someFactory.populateWithParameter(parameter1, parameter2, parameter3, parameter4); 
        a.method_call();
        ....   
    }

the factory goes this way

public class SomeFactory(){

 // some constructor
public A populateWithParameter(SomeClass1 someClass1, SomeClass2 someClass2, String string, int parameter){
 return new A(someClass1, someClass2, string, parameter)
} 
}

and the test is

public void testSomeMethod() throws Exception {
        SomeFactory someFactory = mock(SomeFactory.class);
        when(someFactory.populateWithParameter(
                any(SomeClass1.class), any(SomeClass2.class),
             anyString(), anyInt())).thenReturn(notNull());

        mainActivity.some_method(someFactory);
...
    }

I get this message

org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
4 matchers expected, 1 recorded:
user1611830
  • 4,749
  • 10
  • 52
  • 89

1 Answers1

0

You aren't allowed to use notNull() as a return value. Mockito matchers only stand in for arguments in calls to when and verify, and cannot work as return values. In particular, notNull() will actually return null and mark the "not null" match as a side-effect on a hidden stack, where it lingers until you interact with the mock next (when you actually invoke some_method).

Though you didn't list your stack trace for your InvalidUseOfMatchersException, I'll bet that the error actually happens when you invoke populateWithParameter via some_method, not when you stub populateWithParameter. The "1 recorded" matcher is notNull(), where "4 matchers expected" refer to the number of arguments in the method call. The error message is really tailored for a case where you forget to use a matcher for some argument, like populateWithParameter(any(), any(), anyString(), 42), which is a very common mistake.

Though I see in the comments that "it does not work!" when you try to return an instance, I can guarantee that returning notNull() absolutely will cause a problem, whereas returning an instance may simply reveal a different problem. You may want to update your question with the full stack trace after switching to returning an instance, or ask a new question.

For more information about Mockito matchers behind the scenes, see my question/answer here.

Community
  • 1
  • 1
Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251