How to mock static methods : PowerMock

1. First check versions of Junit being used and download matching PowerMock.
2. Those are the dependencies that you will need if you are using Mockito already:
<dependency org="org.powermock" name="powermock-module-junit4" rev="1.4.12" />
 <dependency org="org.powermock" name="powermock-api-mockito" rev="1.4.12" />
powermock-module-junit4 : this provides integration with Junit4
powermock-api-mockitor : this provides PowerMock classes to work with Mockito
3. Usage is quite simple. Check the link above.
– include those annotations on the class level:
@RunWith(PowerMockRunner.class)
@PrepareForTest(ControllerUtil.class)
– include the following line first (if you have @Before method, it’s best to keep it there)
PowerMockito.mockStatic(ControllerUtil.class);
– do the mocking:
Mockito.when(ControllerUtil.roleExists(anyString())).thenReturn(true);

 

Leave a comment