java – Mockito:想要但没有被引用

我有以下测试方法:

MyClass myClass= Mockito.mock(MyClass.class);
Mockito.when(myClass.methodUsedInMethodBeingTested(Matchers.any(MyTypeParam.class))).thenReturn(Collections.<X, Y> emptyMap());

assertNull(myClass.methodToTest(myObject));
Mockito.verify(myClass).methodUsedInMethodBeingTested(Matchers.any(MyTypeParam.class));

methodUsedInMethodBeingTested是一个我想模拟并返回空映射的方法.但是我收到了失败的消息

Wanted but not invoked myClass.methodUsedInMethodBeingTested()

.

MyClass
{
   public XYZ methodToTest()
   {
    ....
    ....
    Map<X,Y> mp = methodUsedInMethodBeingTested(myTypeParam);
    .....
   }

   public Map<X,Y> methodUsedInMethodBeingTested(MyTypeParam myTypeParam)
   {
    .....
   }
}

解决方法:

你误解了模拟是什么.当你在做的时候

MyClass myClass = Mockito.mock(MyClass.class);
// ...
assertNull(myClass.methodToTest(myObject));

你实际上并没有在真实对象上调用methodToTest.你在mock上调用methodToTest,默认情况下,什么也不做,并返回null,除非它是stubbed.引自Mockito docs

By default, for all methods that return value, mock returns null, an empty collection or appropriate primitive/primitive wrapper value (e.g: 0, false, … for int/Integer, boolean/Boolean, …).

这解释了您的后续错误:该方法实际上未在模拟上调用.

看来你想要的是spy而不是:

You can create spies of real objects. When you use the spy then the real methods are called (unless a method was stubbed).

但是请注意警告:因为它是被调用的真正方法,所以你不应该使用Mockito.when但更喜欢Mockito.doReturn(…).否则,该方法将被调用一次为真.如果你考虑表达式:

Mockito.when(myClass.methodUsedInMethodBeingTested(Matchers.any(MyTypeParam.class))).thenReturn(Collections.<X, Y> emptyMap());
             ^-----------------------------------^
                 this will be invoked by Java

必须计算方法的参数,但这意味着将调用方法methodUsedInMethodBeingTested.由于我们有一个间谍,这是将被调用的真正方法.所以,相反,使用:

MyClass spy = Mockito.spy(new MyClass());
Mockito.doReturn(Collections.<X, Y> emptyMap()).when(spy).methodUsedInMethodBeingTested(Matchers.any(MyTypeParam.class));
assertNull(spy.methodToTest(myObject));
Mockito.verify(spy).methodUsedInMethodBeingTested(Matchers.any(MyTypeParam.class));
上一篇:java – Mockito在使用@Mock时将Null值注入Spring bean?


下一篇:如何使用Mockito模拟For循环