How do I mock a static method that returns void with PowerMock?

Pete picture Pete · Mar 6, 2012 · Viewed 104.7k times · Source

I have a few static util methods in my project, some of them just pass or throw an exception. There are a lot of examples out there on how to mock a static method that has a return type other than void. But how can I mock a static method that returns void to just "doNothing()"?

The non-void version uses these lines of codes:

@PrepareForTest(StaticResource.class)

...

PowerMockito.mockStatic(StaticResource.class);

...

Mockito.when(StaticResource.getResource("string")).thenReturn("string");

However if applied to a StaticResources that returns void, the compile will complain that when(T) is not applicable for void...

Any ideas?

A workaround would probably be to just have all static methods return some Boolean for success but I dislike workarounds.

Answer

Justin Rowe picture Justin Rowe · Jul 2, 2013

You can stub a static void method like this:

PowerMockito.doNothing().when(StaticResource.class, "getResource", anyString());

Although I'm not sure why you would bother, because when you call mockStatic(StaticResource.class) all static methods in StaticResource are by default stubbed

More useful, you can capture the value passed to StaticResource.getResource() like this:

ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
PowerMockito.doNothing().when(
               StaticResource.class, "getResource", captor.capture());

Then you can evaluate the String that was passed to StaticResource.getResource like this:

String resourceName = captor.getValue();