Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does @PrepareForTest in PowerMock really mean?

What does the annotation @PrepareForTest in PowerMockito really mean?

What should be placed there apart of classes which have static methods?

like image 577
Ernesto Avatar asked Jun 03 '19 15:06

Ernesto


People also ask

What does PrepareForTest annotation do?

Annotation Type PrepareForTest This annotation tells PowerMock to prepare certain classes for testing. Classes needed to be defined using this annotation are typically those that needs to be byte-code manipulated.

What is PowerMock in JUnit?

PowerMock is an open-source mocking library for Java applications. It extends the existing mocking frameworks, such as EasyMock and Mockito, to add even more powerful features to them. PowerMock enables us to write good unit tests for even the most untestable code.

What is the difference between Mockito and PowerMock?

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.


1 Answers

That annotation tells PowerMock(ito) that the listed classes will need to be manipulated on the byte code level.

You need to "prepare for test" all these classes X of which you want to

  • mock a static method (on X)
  • gain control over calls to new() used in another class X
  • gain control over private methods (which you do using a spy and
    PowerMockito.when(spy, "privateMethodNameAsString").then...

In other words:

  • To mock X.doStatic(), you have to prepare the class X.
  • To control new Y(...), you have to prepare the class X that contains that new statement.
like image 197
GhostCat Avatar answered Oct 03 '22 22:10

GhostCat