开发者

Using Matchers.any() to match a mock object

开发者 https://www.devze.com 2023-03-14 17:47 出处:网络
Foo mockFoo1 = mock(Foo.class); Foo mockFoo2 = mock(Foo.class); when(((Foo) any()).someMethod()).thenReturn(\"Hello\");
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

精彩评论

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