replace non static method java mock

1k Views Asked by At

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

2

There are 2 best solutions below

0
On

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.

0
On

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.