Mockito:通缉但未被援引

Viv*_*vin 7 java unit-testing 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));
Run Code Online (Sandbox Code Playgroud)

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

想要但没有调用myClass.methodUsedInMethodBeingTested()

.

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

   public Map<X,Y> methodUsedInMethodBeingTested(MyTypeParam myTypeParam)
   {
    .....
   }
}
Run Code Online (Sandbox Code Playgroud)

Tun*_*aki 12

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

MyClass myClass = Mockito.mock(MyClass.class);
// ...
assertNull(myClass.methodToTest(myObject));
Run Code Online (Sandbox Code Playgroud)

你实际上methodToTest并没有调用你的真实物体.你正在调用methodToTestmock,默认情况下,什么都不做并返回null,除非它被存根.引自Mockito文档:

默认情况下,对于返回值的所有方法,mock返回null,空集合或适当的原始/原始包装器值(例如:0,false,...表示int/Integer,boolean/Boolean,...).

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


看来你想要的是一个spy代替:

您可以创建真实对象的间谍.当你使用spy时,会调用真正的方法(除非方法被存根).

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

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

when必须评估方法的参数,但这意味着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));
Run Code Online (Sandbox Code Playgroud)