user3942446 user3942446 - 1 year ago 83
Java Question

Using PowerMockito.whenNew() is not getting mocked and original method is called

I have a code somewhat like this below:

Class A {
public boolean myMethod(someargs) {
MyQueryClass query = new MyQueryClass();
Long id = query.getNextId();
// some more code
Class MyQueryClass {
public Long getNextId() {
//lot of DB code, execute some DB query
return id;

Now I'am writing a test for
. I want to skip the real method
and instead return a stub value. Basically, I want to mock

So in my test case, I have used:

MyQueryClass query = PowerMockito.mock(MyQueryClass.class);

boolean b = A.getInstance().myMethod(args);


I used
in the beginning of my test class.

But when I debug the test, it is still calling the real method
of the

What am I missing here? Can anyone help as I am new to Mockito and PowerMockito.

Answer Source

I think you also need to put the class where the new takes place in the @PrepareForTest annotation - see Mock construction of new objects.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download