I\'m working a bit on an inherited code. I\'ve written a test that is supposed to catch NullPointerException (for it is trying to call a method from null object)
Although it is not good coding practice to mock static method, private method or constructor. But if have some legacy code and you need to mock it. then in that case one can use Powermock with mockito.
Steps to follow when mocking static method using powermock.
1) use specific Runner i.e. PowerMockRunner.class.
2) use annotation @PrepareForTest(UtilityClass.class).
3) initialise utility class containing static method.
4) mock static method you want.
@RunWith(PowerMockRunner.class)
@PrepareForTest(Utility.class)
public class mockingStaticMethod(){
@Mock
Dependency dependency;
@InjectMocks
SystemUnderTest systemUnderTest;
@Test
public void testStaticMethod(){
PowerMockito.mockStatic(Utility.class);
When(Utility.staticMethod(arguments)).thenReturn(expectedValue);
//systemUnderTest class uses the static method present in Utility class
//within the methodCallingStaticMethod()
result = systemUnderTest.methodCallingStaticMethod();
assertEquals(expectedValue, actualValue);
}
}