06: Mockito & PowerMock for mocking static methods

This extends Part 4: Mockito & PowerMock for partially mocking private methods to mock “static” methods.

How to use both Spring JUnit and PowerMock runners?

By using the “@PowerMockRunnerDelegate” from the “powermock-module-junit4” jar.

So, need to use compatible “Mockito” and “PowerMock”.

PowerMock & Mockito version compatibility

PowerMock & Mockito version compatibility

Step 1: Add “PowerMock” libraries to the pom.xml

Step 2: Service layer interfaces and implementations + utility class that has a static method, and which needs to be mocked with “PowerMock”.

Service Layer
Utility Class

This static method will be mocked by the “PowerMock”.

Step 3: Now the JUnit class that mocks “SimpleServiceImpl” where the method “SimpleUtil.getUserById(int id)” with the help of PowerMock.

Note:

1) @RunWith(PowerMockRunner.class)

2) @PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)

3) @PrepareForTest(SimpleServiceImpl.class)

4) PowerMockito.mockStatic(SimpleUtil.class);

5) PowerMockito.when(SimpleUtil.getUserById(Mockito.anyInt())).thenReturn(“Sam”);

final methods

It will work if you you add the “final” modfier to the method “SimpleUtil.getUserById(int id)”. So, PowerMock is required to mock private, static, and final methods.


Java developer & architect Q&As

Java developers Q&As

Top