I am trying to capture the 'logError' method in a static class (in the sense of every method/field is static), and verify it has been called some number of times by other methods in the same class.
this method is:
public static void logError(Object message){
LOGGER.error(message); // static logger
}
my attempt to test it:
@Test
public void errLogTest() throws Exception{
PowerMockito.mockStatic(X.class);
PowerMockito.doNothing().when(X.class);
X.logError(Mockito.anyString());
X.open();
X.open(); //should log error for opening twice
PowerMockito.verifyStatic(Mockito.times(1));
}
My problem is, no matter how many times I specify, it passes. I removed mocking behavior and know for a fact the logger is called once, but I can have PowerMockito.verifyStatic(Mockito.times(9001));
instead and it still passes. How do I test this?
You're missing a line of code after verifyStatic
. You're not telling PowerMock what to verify. You're also mocking all static methods of the class instead of just the one you don't want called.
@Test
public void errLogTest() throws Exception{
PowerMockito.spy(X.class); //Used to be: PowerMockito.mockStatic(X.class);
PowerMockito.doNothing().when(X.class);
X.logError(Mockito.anyString());
X.open();
X.open(); //should log error for opening twice
PowerMockito.verifyStatic(Mockito.times(1));
X.logError(Mockito.anyString()); //Now verifyStatic knows what to verify.
}
You may still need to do some debugging because, in my experience, setting up the expectations sometimes calls the underlying method anyway.
Here's the javadoc for spy
: http://static.javadoc.io/org.powermock/powermock-api-mockito/1.5.4/org/powermock/api/mockito/PowerMockito.html#spy(java.lang.Class)
Here's the javadoc for verifyStatic
: http://static.javadoc.io/org.powermock/powermock-api-mockito/1.5.4/org/powermock/api/mockito/PowerMockito.html#verifyStatic(org.mockito.verification.VerificationMode)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With