替换非静态方法java模拟
我需要模拟对象的公共非静态方法。
问题是我无法创建模拟对象,因为该对象是直接在代码中创建的。
我尝试使用 PowerMockito.spy() 和 PowerMockito.when(...) 监视类,但它不起作用(可能是因为 PowerMockito.when 仅适用于静态和私有方法)
例如,假设我需要测试这:
... myClass anObject = new myClass(); anObject.aMethod();
...
我如何模拟调用 anObject.aMethod() ?
我想我需要监视我的班级,但它不起作用..
I need to mock a public, non-static method of an object.
The problem is that I ca'nt create a mock object, because this object is created directly in the code.
I have tried spying the class using PowerMockito.spy() and PowerMockito.when(...) but it didn't work (maybe its because PowerMockito.when only works for static and private methods)
For example, suppose I need to test this:
...
myClass anObject = new myClass();
anObject.aMethod();
...
How could I mock the call anObject.aMethod() ??
I guess I need to spy myClass, but it didn't work..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用依赖注入。
在最简单的情况下,只需将工厂对象传递给创建对象的方法,然后监视该工厂。
另一种方法是将工厂传递给对象的构造函数。
Use dependency injection.
In simplest case, just pass the factory object to the method that creates your object, and then spy that factory.
Other way of doing this is to pass the factory to the constructor of your object.
最好重构代码以使用依赖项注入。
但快速谷歌一下后建议您实际上可以在 PowerMockito 中对构造函数进行存根处理。请参阅whenNew 的 javadoc。
我不能保证这一点,因为我没有使用过 PowerMockito,但这看起来应该允许你让你的构造函数调用返回一个模拟对象。
It's likely best to refactor your code to use dependency injection.
But a quick google suggests that you can actually stub the constructor in PowerMockito. See javadoc for whenNew.
I can't vouch for it as I haven't used PowerMockito, but this looks like it should allow you to make your constructor call return a mock object.