开发者

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 sta开发者_如何学JAVAtic 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..


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. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜