Mockito Mock Static Method - PowerMock With Examples

Mockito allows us to create mock objects. Since static method belongs to the class, there is no way in Mockito to mock static methods. However, we can use PowerMock along with Mockito framework to mock static methods.

Mockito Mock Static Method using PowerMock

PowerMock provides different modules to extend Mockito framework and run JUnit and TestNG test cases.

Note that PowerMock doesn’t support JUnit 5 yet, so we will create JUnit 4 test cases. We will also learn how to integrate TestNG with Mockito and PowerMock.

PowerMock Dependencies

We need following PowerMock dependencies for mocking static methods in Mockito.

  • powermock-api-mockito2: This is the core PowerMock dependency and used to extend Mockito2 mocking framework. If you are using Mockito 1.x versions then use powermock-api-mockito module.
  • powermock-module-junit4: For running JUnit 4 test cases using PowerMock.
  • powermock-module-testng: For running TestNG test cases and supporting PowerMock.

Below is the final pom.xml from our project.

Note that I am using 2.0.0-beta.5 version of PowerMock. This version supports Java 10, however, it’s still in beta so there might be some issues present in complex cases.

When I tried to use current stable version 1.7.x, I got the following errors.

Here are GitHub issues opened for this exception – issue1 and issue2.

Let’s create a simple class with a static method.

JUnit Mockito PowerMock Example

We need to do the following to integrate PowerMock with Mockito and JUnit 4.

  • Annotate test class with @RunWith(PowerMockRunner.class) annotation.
  • Annotate test class with @PrepareForTest and provide classed to be mocked using PowerMock.
  • Use PowerMockito.mockStatic() for mocking class with static methods.
  • Use PowerMockito.verifyStatic() for verifying mocked methods using Mockito.

Here is a complete example of mocking static method using Mockito and PowerMock in JUnit test case.

TestNG Mockito PowerMock Example

For TestNG test cases, we don’t need to use @RunWith annotation. We need test classes to extend PowerMockTestCase so that PowerMockObjectFactory is used to create test class instance.

Summary

PowerMock provides extended features for Mockito, one of them is the ability to test static methods. It’s easily integrated with JUnit 4 and TestNG. However, there is no near-term support plan for JUnit 5.

By admin

Leave a Reply

%d bloggers like this: