Mockito 用 Spring 进行模拟:“传递给 verify() 的参数不是模拟!”
我使用 此博客 中的代码在我的单元测试中注入 Mockito 模拟。然而,在自动装配模拟之前,它会被 Spring 包装在 JDK 代理中。这会导致任何 verify(autowiredMock) 抛出“传递给 verify() 的参数不是模拟!”。当 Mockito 检查传递给 verify(..) 的参数是否是此方法中有效的 Mockito 模拟对象时,会引发异常:
private static Method getCallbacksSetter(Class type, String methodName) throws NoSuchMethodException {
return type.getDeclaredMethod(methodName, new Class[]{ Callback[].class });
}
我的问题是如何告诉 Spring 不要代理我在 BeanFactoryPostProcessor 中注册的 Mockito 模拟 bean?请注意,我想避免设置 proxy-target-class="true"。
谢谢
I used the code from this blog to inject Mockito mocks in my unit tests. However, before the mock is autowired it gets wrapped by Spring in a JDK proxy. This causes any verify(autowiredMock) to throw "Argument passed to verify() is not a mock!". The exception is thrown when Mockito is checking that the argument passed to verify(..) is a valid Mockito mock object in this method:
private static Method getCallbacksSetter(Class type, String methodName) throws NoSuchMethodException {
return type.getDeclaredMethod(methodName, new Class[]{ Callback[].class });
}
My question is how to tell Spring not to proxy Mockito mock beans which I register in the BeanFactoryPostProcessor? Please note that I would like to avoid setting proxy-target-class="true".
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您将模拟自动装配到 setter 方法中,则可以在那里手动将其解包。
它很丑陋,但它是一种没有 proxy-target-class 的出路。
顺便说一句,如果模拟给你带来了这么大的痛苦,你难道不应该考虑一个存根解决方案吗?
If you autowire the mock into a setter method, you can unwrap it manually there.
It's ugly, but it is a way out without
proxy-target-class
On a side note, if mocking is giving you this much pain, shouldn't you be looking at a stub solution?
最新版本的 Mockito(当前为 1.9.0)已修复此问题,更改了检测对象是否为模拟对象的算法。
Latest version of Mockito (currently 1.9.0) has fixed this issue changing the algorithm that detects whether an object is a mock or is not.