public class ClassWithPrivateStaticMethods {
private static String getParam(String paramName) {
String result = "";
...
...
return result;
}
private static String getDetail(String contextName) {
String result = "";
String temp = getParam(tempParamName);
...
return result;
}
}
PowerMockito.mockStatic(ClassWithPrivateStaticMethods.class);
PowerMockito.when(ClassWithPrivateStaticMethods.class, "getParam", Mockito.anyString()).thenReturn("dummy");
Problem
PowerMockito.mockStatic() actually mocks all the static method in the class.So if you have the circumstance where you want to mock one static method, but you want other method to run normally, then this method will not work. Because the other method will also be mocked.
PowerMockito.mockStatic(ClassWithPrivateStaticMethods.class)
PowerMockito.when(ClassWithPrivateStaticMethods.class, "getParam", Mockito.anyString()).thenReturn("dummy");
String result = Whitebox.invokeMethod(ClassWithPrivateStaticMethods.class, "getDetail", Mockito.anyString());
Solution - Partial Mocking
We can solve this by mocking individual static methods by following way:
PowerMockito.spy(ClassWithPrivateStaticMethods.class);
PowerMockito.doReturn("dummy").when(ClassWithPrivateStaticMethods.class, "getParam", Mockito.anyString())
String finalResult = Whitebox.invokeMethod(ClassWithPrivateStaticMethods.class, "getDetail", Mockito.anyString());
No comments:
Post a Comment