Mockito间谍-在间谍对象中调用内部类方法而不是间谍方法时 [英] Mockito spy - when calling inner class method not spying method in spy object

查看:184
本文介绍了Mockito间谍-在间谍对象中调用内部类方法而不是间谍方法时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个内部类如下:

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:

And the mockito test is looking as following: 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从未被检测为已调用",尽管在日志中我看到它是.什么地方出了错? :)

The first test is working as expected. The second one the innerFunc is never detected as "invoked", although in the log I see it is.What is wrong? :)

谢谢!

推荐答案

怎么了?

好吧,这里的问题非常细微,当您调用Mockito.spy(p)时,mockito在幕后为ClassWithInnerObject实例创建了某种装饰器,从而可以监视实例上的所有方法调用.因此,您可以检查给定方法被调用多少次,但只能在装饰器上而不在您的实例上.在这里,当您使用内部类时,它将在您的ClassWithInnerObject实例上调用innerFunc()而不是在装饰器上调用,因此对于Mockito innerFunc() 未被调用.

Well, the problem here is quite subtle, when you call Mockito.spy(p), mockito creates behind the scene some kind of decorator over your instance of ClassWithInnerObject allowing to monitor all methods calls on your instance. Thanks to that, you can check how many times a given method has been called but on the decorator only not on your instance. And here, when you use an inner class, it calls innerFunc() on your instance of ClassWithInnerObject not on the decorator so for Mockito innerFunc() has not been called.

这篇关于Mockito间谍-在间谍对象中调用内部类方法而不是间谍方法时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆