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

As @TrueDub mentioned in his accepted reply, you need to add the class where the constructor is called to the @PrepareForTest.

However, if you do this, coverage for that class as reported by eclemma and Sonar will be zero for that class

Powermockito wiki

We are going to replace Javassist with ByteBuddy (#727) and it should help to resolve this old issue. But right now there is NO WAY TO USE PowerMock with JaCoCo On-the-fly instrumentation. And no workaround to get code coverage in IDE.

So the solution here would be to refactor the actual code to use a static factory that would return an instance of that class and then statically mock it.


You need to put the class where the constructor is called into the @PrepareForTest annotation instead of the class which is being constructed - see Mock construction of new objects.

In your case:

@PrepareForTest(MyQueryClass.class)

@PrepareForTest(A.class)

More general:

@PrepareForTest(NewInstanceClass.class)

@PrepareForTest(ClassThatCreatesTheNewInstance.class)