Search code examples
javatddmockingmockitomatcher

Using Matchers.any() to match a mock object


Foo mockFoo1 = mock(Foo.class);
Foo mockFoo2 = mock(Foo.class);
when(((Foo) any()).someMethod()).thenReturn("Hello");

In the above sample code, line 3 fails with a NullPointerException. Why so?

My thought on this:

EITHER.. any() should be used for matching parameters rather than matching the objects on which methods are triggered.

OR .. any() works only for real concrete objects and not mock objects.


Solution

  • You need to do:

    Foo mockFoo1 = mock(Foo.class);
    Foo mockFoo2 = mock(Foo.class);
    when(mockFoo1).someMethod().thenReturn("Hello");
    when(mockFoo2).someMethod().thenReturn("Hello");
    

    any() (shorter alias to anyObject()) is an Mockito argument matcher that matches any argument and only should be used as follows:

    when(mockFoo1.someMethod(any())).thenReturn("Hello");
    

    any() returns null, so your code was equivalent to

    when(((Foo) null).someMethod()).thenReturn("Hello");