Understanding @PrepareForTest

PrepareForTest is very powerful tool that unlocks class manipulation capabilities by modifying class to byte code level.

PowerMock is a powerful library that works on byte code level of our program.

PrepareForTest annotation

PrepareForTest has one job, it will creates a reflection of your class at bytecode level. It allows you to manipulate your source code such that you can change behavior (implementation) of declared methods.

This comes handy when you are working with class or methods that are now allowed to be mocked by Java Reflection.

Here are some f the use cases for PrepareForTest:

Mock static methods:

@RunWith(PowerMockRunner.class)
@PrepareForTest({
 ClassWithStaticMethods.class,
})
public class ClassToTest {
 @Before
 public void setUp() throws Exception {
     PowerMockito.mockStatic(ClassWithStaticMethods.class);
     PowerMockito.when(ClassWithStaticMethods.staticMethod()).thenReturn(someValue);
 }
}

Mock final classes/methods:

Mockito cannot mock final methods even if you have created mock of that class. To mock these methods, we need to prepare that class and mock it with PowerMockito.mock().

Inject with PowerMockito.whenNew()

When you need to inject a mock instead of creating an actual instance of a class, you can use PowerMockito.whenNew(). This will inject your mock whenever new instance is created in your source class.

In this example class, we are creating CustomClass without any injection mechanism, we can inject our mock by adding ExampleClass in PrepareForTest and using PowerMockito.whenNew():

To suppress(), stub() or replace() any method of a Class. You can modify behavior of methods declared in any class, You can:

suppress() methods and constructors.

stub() methods to return different value.

replace() methods to return different value depending on parameter supplied.

Last updated