Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

What is PowerMockito whenNew?

PowerMockito. whenNew is a powerful function to stub a constructor. This article will demonstrate some scenario when we use whenNew and some gotchas I encountered along the way. Let's say we have two classes, BookDao and BookRepository.

What is the difference between Mockito and PowerMockito?

While Mockito can help with test case writing, there are certain things it cannot do viz:. mocking or testing private, final or static methods. That is where, PowerMockito comes to the rescue. PowerMockito is capable of testing private, final or static methods as it makes use of Java Reflection API.

Can we mock constructor using Mockito?

Starting with Mockito version 3.5. 0, we can now mock Java constructors with Mockito. This allows us to return a mock from every object construction for testing purposes.

Should we use PowerMockito?

Power Mock gives you access to mock static methods, constructors etc. and this means that your code is not following best programming principles. Power Mock should be used in legacy applications where you cannot change the code which has been given to you.


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)


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.