5

我正在尝试验证是否在我模拟的对象上调用了一个方法:

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)中调用的任何方法

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

4

1 回答 1

4

不,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" );

我希望这是有道理的,并且对您有所帮助。

干杯,

于 2013-02-04T08:37:36.597 回答