0

Mockito official doc says:

Warning:

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

E.g: (example shows verification but the same applies to stubbing):

verify(mock).someMethod(anyInt(), anyString(), eq("third argument"));
//above is correct - eq() is also an argument matcher

verify(mock).someMethod(anyInt(), anyString(), "third argument");
//above is incorrect - exception will be thrown because third argument is given without argument matcher. 

Matcher methods like anyObject(), eq() do not return matchers. Internally, they record a matcher on a stack and return a dummy value (usually null).

I am curious why it is impossible to use Mathers alongside values even though any()-like methods return null.

gorodkovskaya
  • 333
  • 3
  • 15
  • Because Mockito can't tell the difference between `method(null, any())` and `method(any(), null)`. I wrote a longer answer about it here: [How do Mockito matchers work?](https://stackoverflow.com/questions/22822512/how-do-mockito-matchers-work) – Jeff Bowman Feb 09 '18 at 01:13

2 Answers2

1

The documentation says

Matcher methods like anyObject(), 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 anyObject(), eq() methods outside of verified/stubbed method.

Mockito relies on this arguably black magic. If you were able to pass objects, Mockito would have to be able to understand when null is an actual argument, and when it is a matcher invocation. Pretty much, these two situations would be indistinguishible (I assume):

verify(mock).someMethod(anyInt(), anyString(), null);
verify(mock).someMethod(anyInt(), null, anyString());
kutschkem
  • 7,826
  • 3
  • 21
  • 56
0

A good guess is that mockito need to find argument matchers for all the arguments in an OngoingStubbing. In ArgumentMatcherStorageImpl#validateState() seeks matchers for every method argument.