Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verifying a call of a static void method with powermockito

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?

like image 843
AdamSpurgin Avatar asked Mar 04 '14 19:03

AdamSpurgin


1 Answers

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)

like image 64
Matt Lachman Avatar answered Sep 25 '22 15:09

Matt Lachman