我正在尝试验证是否在我模拟的对象上调用了方法:
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)
我希望我的问题和代码很清楚
不,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)
我希望这是有道理的,并对你有一点帮助。
干杯,
| 归档时间: |
|
| 查看次数: |
13465 次 |
| 最近记录: |