YON Blog

Mockito spy partial mocking

Mockito 官方文档在讲解 spy 时说到, 在 v1.8 之前 Mockito 的 partial mocking 不是真正的 partial mocking. 一开始没有理解这句话, 还把 v1.7 的版本下载到本地查看 Javadoc, 发现两个版本的表述基本一致. 那到底真正的 partial mocking 和不是真正的 partial mocking 的区别在哪里呢? 结合这个提问 https://stackoverflow.com/questions/4246088/unit-testing-with-mockito-partial-mocking 我的理解是, 这两者的区别就在于 mock 实现的方式上, 真正的 partial mocking 是把需要 mock 的方法真的修改掉, 非真正 partial mocking 的实现方式就是做了一层动态代理 (使用动态代理我们知道, 在方法内部被调用的方法是无法被代理的). 这就是 Mockito v1.7 在讲解 spy 时提到的这句话的含义:

Spying on real objects is often associated with “partial mocking” concept. However, Mockito spies are not partial mocks. Mockito spy is meant to help testing other classes - not the spy itself. Therefore spy will not help if you intend to verify if method calls other method on the same object. In this case I suggest being OO/SRPy (for example you might extract new class/interface…)