2016-02-19 22 views
2

我有以下的测试方法:的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) 
    { 
    ..... 
    } 
} 

回答

7

你误解了模拟是什么。当你在做

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

你实际上没有调用methodToTest对你的真实物体。您在模拟上调用methodToTest,默认情况下,它不会执行任何操作并返回null,除非它被截断。从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(...).when否则该方法将被实际调用一次。如果你考虑表达式:

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

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

感谢您的回答。我有两个疑问:1.我无法做到这一点MyClass spy = Mockito.spy(MyClass.class);因为它说Type mIsmatch无法从类转换为MyClass。 2.你能否更好地解释这个问题“虽然有一个警告:因为它是真正的方法被调用,所以你不应该使用Mockito.when,而应该选择Mockito.doReturn(...),否则该方法会被称为一次真实:“ – Kode

+0

@Vwin我编辑过。我使用了一种不能在您的Mockito版本中出现的新方法。为了您的第二个顾虑,我也澄清了。 – Tunaki

+0

这是完美的。有效。感谢@RomanVottner。谢谢Tunaki,你真棒:)而且解释变得更有意义。 – Kode

1

您正在调用模拟实例上的methodToTest。因为你还没有配置它,只是返回null,它不会尝试调用任何实际的方法的实现。