Mocking Static Methods That Return void in Java

This is one of those things that I tend to do on a regular basis . . . but unfortunately don’t remember the details each time, so I am adding it for future reference.

Often, developers will want to mock static methods that return void.  The Mockito and PowerMockito frameworks provide for this, but the syntax isn’t immediately obvious.

Following is an example.

public class SomeClass {
    public static void doSomething(String arg1, int arg2) {
        // Method that does something...
    }
}
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

/*
 * The RunWith and PrepareForTest annotations are following annotations are
 * necessary to mock the static methods in the SomeClass class. The RunWith
 * enables the class to be run via PowerMock, and the PrepareForTest is an array
 * of the classes with static members that we want to mock.
 *
 * The PowerMockIgnore annotation tells PowerMock to defer the loading of
 * classes with the names supplied to the system classloader.  This will vary
 * depending on the dependency tree that you are using/testing.  It is also
 * not necessary, but here for example purposes.
 */
@RunWith(PowerMockRunner.class)
@PowerMockIgnore({
    "javax.management.*",
    "javax.net.ssl.*",
    "org.apache.log4j.*"
})
@PrepareForTest({ SomeClass.class })
public class SomeTestClass {
@Test
    public void shouldDoSomethingExpected() throws Exception {
         // Set up the SomeClass's static members for mocking
        PowerMockito.mockStatic(SomeClass.class);

        // Configure the mock for the method in question.
        // The following syntax is what is key here
        PowerMockito.doNothing()
            .when(
                SomeClass.class,
                "doSomething",
                Mockito.anyString(),
                Mockito.anyInt());
    }
}

   

       

       

Leave a Reply