简体   繁体   English

替换非静态方法java mock

[英]replace non static method java mock

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) 我尝试使用PowerMockito.spy()和PowerMockito.when(...)来监视类,但是它不起作用(也许是因为PowerMockito.when仅适用于静态和私有方法)

For example, suppose I need to test this: 例如,假设我需要测试这个:

... myClass anObject = new myClass(); ... myClass anObject = new myClass(); anObject.aMethod(); anObject.aMethod();
... ...

How could I mock the call anObject.aMethod() ?? 我如何模拟调用anObject.aMethod()?

I guess I need to spy myClass, but it didn't work.. 我想我需要监视myClass,但它不起作用..

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. 这样做的另一种方法是将工厂传递给对象的构造函数。

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. 但是一个快速的谷歌建议你实际上可以在PowerMockito中存根构造函数。 See javadoc for whenNew . 有关whenNew,请参见javadoc

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. 我不能担保它,因为我没有使用过PowerMockito,但这看起来应该可以使您的构造函数调用返回一个模拟对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM