[英]Mockito spy - when calling inner class method not spying method in spy object
我有内部类的类如下:
public class ClassWithInnerObject {
private final InnerObject innerObject;
public ClassWithInnerObject() {
innerObject = new InnerObject();
}
public void callInnerObjectMethod() {
innerObject.outerFunc();
}
public void outerFunc() {
innerFunc();
}
public void innerFunc() {
Log.d("XXX", "innerFunc: called");
}
public class InnerObject {
public void outerFunc() {
innerFunc();
}
}
}
而 mockito 测试看起来如下:build.gradle:
androidTestCompile 'junit:junit:4.12'
androidTestCompile 'org.mockito:mockito-core:1.10.19'
androidTestCompile 'com.crittercism.dexmaker:dexmaker:1.4'
androidTestCompile 'com.crittercism.dexmaker:dexmaker-mockito:1.4'
androidTestCompile 'com.crittercism.dexmaker:dexmaker-dx:1.4'
测试:
@RunWith(AndroidJUnit4.class) public class SpyVerifyTest {
@Test public void myInnerTestWorking() {
ClassWithInnerObject p = new ClassWithInnerObject();
ClassWithInnerObject spy = Mockito.spy(p);
spy.outerFunc();
verify(spy, times(1)).innerFunc();
}
@Test public void myInnerTestNotWorking() {
ClassWithInnerObject p = new ClassWithInnerObject();
ClassWithInnerObject spy = Mockito.spy(p);
spy.callInnerObjectMethod();
verify(spy, times(1)).innerFunc();
}
}
第一个测试按预期工作。 第二个innerFunc
从未被检测为“调用”,尽管在日志中我看到它是。有什么问题? :)
谢谢!
怎么了?
嗯,这里的问题很微妙,当你调用Mockito.spy(p)
, mockito
在你的ClassWithInnerObject
实例上创建了某种装饰器,允许监视实例上的所有方法调用。 多亏了这一点,您可以检查给定方法被调用了多少次,但只能在装饰器上而不是在您的实例上。 在这里,当您使用内部类时,它会在您的ClassWithInnerObject
实例上调用innerFunc()
而不是在装饰器上调用,因此对于Mockito
innerFunc()
没有被调用。
您可以使用“ClassWithInnerObject.this”来修复该问题。 在内部类。
public class InnerObject {
public void outerFunc() {
ClassWithInnerObject.this.innerFunc();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.