Dear stackoverflow comrades, I again have a problem in getting a specific PowerMock / Mockito case to work. The issue is, that I need to verify the call of a private static method, which is called from a public non-static method. A similar example I posted previously on How to suppress and verify private static method calls?
This is my code:
class Factory {
public String factorObject() throws Exception {
String s = "Hello Mary Lou";
checkString(s);
return s;
}
private static void checkString(String s) throws Exception {
throw new Exception();
}
}
And this is my testclass:
@RunWith(PowerMockRunner.class)
@PrepareForTest(Factory.class)
public class Tests extends TestCase {
public void testFactory() throws Exception {
Factory factory = mock(Factory.class);
suppress(method(Factory.class, "checkString", String.class));
String s = factory.factorObject();
verifyPrivate(factory, times(8000)).invoke("checkString", anyString());
}
}
The problem here is, that the Test is successful, but it shouldn't be. It shouldn't be because the private static method should be called exactly 1 times. But no matter what value I put in times(), it always verifies it as true... halp :(
Ok, I think I found the answer, but it was a headache. Rudy gave me the final hint with using using a spy, but it was still not trivial (although the solution looks "baby-easy"). Here is the complete solution:
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.times;
import static org.powermock.api.mockito.PowerMockito.verifyPrivate;
import static org.powermock.api.mockito.PowerMockito.doNothing;
import static org.powermock.api.mockito.PowerMockito.spy;
@RunWith(PowerMockRunner.class)
@PrepareForTest(Factory.class)
public class Tests extends TestCase {
public void testFactory() throws Exception {
Factory factorySpy = spy(new Factory());
String s = factorySpy.factorObject();
doNothing().when(factorySpy, "checkString", anyString());
verifyPrivate(factorySpy, times(1)).invoke("checkString", anyString());
}
}
来源:https://stackoverflow.com/questions/16515809/powermock-verify-private-static-method-call-in-non-static-method