Mockito verify 方法不检测方法调用

Rya*_*yan 5 java 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
}
Run Code Online (Sandbox Code Playgroud)

这不是我的确切代码,但它模拟了我想要做的事情。当尝试验证是否被调用时,代码将失败otherMethod()。它是否正确?我对该verify方法的理解是,它应该检测存根方法中调用的任何方法 ( someMethod)

我希望我的问题和代码很清楚

And*_*rup 4

不,Mockito 模拟只会在所有调用中返回 null,除非您使用例如覆盖。thenReturn()ETC。

您正在寻找的是 a @Spy,例如:

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

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

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

public String someMethod(int arg){
    otherClass.methodWeWantMocked();
    otherMethod();
    return "";
}
Run Code Online (Sandbox Code Playgroud)

因此

MyClass mc = new MyClass();
OtherClass oc = Mockito.mock( OtherClass.class );
mc.setOtherClass( oc );
Mockito.when( oc.methodWeWantMocked() ).thenReturn( "dummy" );
Run Code Online (Sandbox Code Playgroud)

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

干杯,

  • @Ryan:嘲笑一个对象意味着:我不在乎你在现实中做什么。而是按照我告诉你的去做。因此,`someMethod()` 的实现被替换为 `return "test";`(如果使用 0 作为参数调用)。您通常会模拟依赖项,即被测试类使用的对象,而不是模拟被测试类本身。然后你可以验证被测试的类是否调用了依赖项。 (2认同)