开发者

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?

开发者_Python百科

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.


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");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜