2013-02-04 125 views
2

我正在尝试验证的方法被调用,我嘲笑的对象上:验证的Mockito方法无法检测方法调用

public class MyClass{ 
    public String someMethod(int arg){ 
     otherMethod(); 
     return ""; 
    } 

    public void otherMethod(){ } 
}  

public void testSomething(){ 
    MyClass myClass = Mockito.mock(MyClass.class); 

    Mockito.when(myClass.someMethod(0)).thenReturn("test"); 

    assertEquals("test", myClass.someMethod(0)); 

    Mockito.verify(myClass).otherMethod(); // This would fail 
} 

这不是我的确切的代码,但它模拟了我正在努力。当试图验证otherMethod()被调用时,代码将失败。它是否正确?我的verify方法的理解是,它会自动侦测被称为存根方法(someMethod

我希望我的问题和代码是明确

回答

3

不,的Mockito模仿只会返回null上所有调用的任何方法,除非你用例如重写。 thenReturn()

什么你要找的是一个@Spy,例如:

MyClass mc = new MyClass(); 
MyClass mySpy = Mockito.spy(mc); 
... 
mySpy.someMethod(0); 
Mockito.verify(mySpy).otherMethod(); // This should work, unless you .thenReturn() someMethod! 

如果你的问题是someMethod()包含您不想执行的代码,而是嘲笑,然后注入模拟,而不是嘲笑方法调用本身,例如:

OtherClass otherClass; // whose methods all throw exceptions in test environment. 

public String someMethod(int arg){ 
    otherClass.methodWeWantMocked(); 
    otherMethod(); 
    return ""; 
} 

从而

MyClass mc = new MyClass(); 
OtherClass oc = Mockito.mock(OtherClass.class); 
mc.setOtherClass(oc); 
Mockito.when(oc.methodWeWantMocked()).thenReturn("dummy"); 

我希望这是有道理的,并帮助你一点。

干杯,

+0

感谢这个,但如果我想使用'.thenReturn()''上someMethod'以及验证'otherMethod'被调用呢? 此外,不这样则嘲讽类时呈现'verify'没用? – Ryan

+2

@Ryan:嘲笑一个对象意味着:我不在乎你在现实中做了什么。做我告诉你要做的。所以'someMethod()'的实现被替换为'return“test”;'(如果调用0作为参数)。您通常会模拟依赖项,即被测试类所使用的对象,而不是模拟被测试的类本身。然后你可以验证被测试的类已经调用了依赖关系。 –

+1

间谍和模拟是两回事,你应该首先明白!它们的行为不同,在单元测试方面使用方式不同。如果问题是,里面有'代码的someMethod()',你不想被调用,那么您应该嘲笑的代码,而不是嘲讽'的someMethod()'调用。 –

相关问题