PowerMock: Testing Tool Or Testing Obstacle

New features are making programming easier compared to how it was a few years back. Some tools required deep knowledge about the new features, one of them is PowerMock. PowerMock is a great tool, like a magic tool.

What is PowerMock?

"PowerMock is a framework that extends other mock libraries such as EasyMock with more powerful capabilities. PowerMock uses a custom classloader and bytecode manipulation to enable mocking of static methods, constructors, final classes and methods, private methods, removal of static initializers and more."

Why use it?

PowerMock allows mocking static or final classes that can not be mocked in Mockito. It sounds great! It can mock anything that might not be the correct way of accessing objects in Java.

Still, PowerMock is not recommended. Why?

1. Sacrificing good design code

We invest more time to design good code to make code flexible enough to use in the future. Testing good code is easy but if the code design is bad and we want to test it, It becomes a challenging job. PowerMock allows testing bad code without changing it to good code.

Avoiding PowerMock in the early stage will make code better instead of creating tech debt with bad code. Using PowerMock in big applications makes testing all the more difficult.

Initially PowerMock documentation itself mentions - "compromise with good design"


2. Mocking private methods

PowerMock can mock a private method of a class, cool!

Wait, is a private method supposed to be mocked?

No, if we mock private methods then the test escapes that method's logic to be tested. It will reduce the chance of detecting bugs. Instead of mocking a private method, it is better to mock external dependencies.

3. Using PowerMock without understanding testing

To use PowerMock we need to have deep knowledge of testing(especially mocking). Lack of knowledge about PowerMock could lead an application to crash.

Before using PowerMock, check compatibility with the framework and have a look at the known issues.

A quote from PowerMock site

How to avoid PowerMock?

We can write tests in a way that can avoid PowerMock. Alternative ways of writing tests are described in the On PowerMock abuse blog.

An example of using PowerMockito

An example of UserController using spring boot and java where it has a method called createUserId. createUserId generates id using a user name and randomUUID.

randomUUID is a static method that can be tested using PowerMockito.

To test a method that uses randomUUID we can use PowerMockito. Remember, that randomUUID is a static method.


As PowerMock is a powerful tool, we need to learn where to use it. It can be useful when the project is completely messed up and there is no other way to test it. We can not completely avoid PowerMock in cases such as random functionality. But most of the time, PowerMock is a quick hack for testing poorly designed code.

Preeti Sharma