75

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.

Elrond_EGLDer
  • 47,430
  • 25
  • 189
  • 180
Pete
  • 9,930
  • 22
  • 87
  • 134
  • Is the question for PowerMockito or PowerMock ? The title suggests PowerMock but looks like you r using PowerMockito. – xpioneer Aug 03 '18 at 12:28

4 Answers4

86

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();
Justin Rowe
  • 2,138
  • 1
  • 18
  • 14
43

You can do it the same way you do it with Mockito on real instances. For example you can chain stubs, the following line will make the first call do nothing, then second and future call to getResources will throw the exception :

// the stub of the static method
doNothing().doThrow(Exception.class).when(StaticResource.class);
StaticResource.getResource("string");

// the use of the mocked static code
StaticResource.getResource("string"); // do nothing
StaticResource.getResource("string"); // throw Exception

Thanks to a remark of Matt Lachman, note that if the default answer is not changed at mock creation time, the mock will do nothing by default. Hence writing the following code is equivalent to not writing it.

doNothing().doThrow(Exception.class).when(StaticResource.class);
StaticResource.getResource("string");

Though that being said, it can be interesting for colleagues that will read the test that you expect nothing for this particular code. Of course this can be adapted depending on how is perceived understandability of the test.


By the way, in my humble opinion you should avoid mocking static code if your crafting new code. At Mockito we think it's usually a hint to bad design, it might lead to poorly maintainable code. Though existing legacy code is yet another story.

Generally speaking if you need to mock private or static method, then this method does too much and should be externalized in an object that will be injected in the tested object.

Hope that helps.

Regards

Niks
  • 4,582
  • 4
  • 31
  • 50
Brice
  • 33,480
  • 7
  • 78
  • 93
  • 2
    unfortunately that won't work as when() only accepts a variable and StaticResource is a type. (`StaticResource cannot be resolved to a variable`) – Pete Mar 06 '12 at 14:43
  • Oh yeah sorry, you are correct my code is wrong, I'm to acustomed to non static mocks. Anyway I updated my ansswer to reflect the correct syntax. – Brice Mar 06 '12 at 16:14
  • Thanks! So having static helper methods that have no dependencies is a bad idea? Of course I could just inject and object that does the work but it feels like it makes sense to put workers that have no dependencies in a static object to signify their independence.. – Pete Mar 07 '12 at 06:35
  • What I meant is if your static helper methods need to be mocked, then you may seriously consider injecting a collaborator. _A contrario_ you never need to mock StringUtils, Iterables, or anything else. Also don't forget we are using an object oriented language, it's all about messaging between objects (quoting Alan Kay). If you are interested, there's a great book : [Growing Object Oriented Software Guided by Tests](http://www.growing-object-oriented-software.com/). Regards :) – Brice Mar 07 '12 at 11:26
  • The leading `doNothing()` call is redundant. You only need `doThrow(new Exception()).when(StaticResource.class);` on that line. – Matt Lachman Jul 02 '13 at 12:10
  • @MattLachman Thanks I spotted an unclear use of the API. The line of code in the answer will make the mock **do nothing** on the **first** call, **then** on the **second** call the mock will throw an exception. You are indeed right: by default on mocks methods do nothing by default (if the default is not changed at mock creation). That being said, it _can_ a good idea to even write the `doNothing` behavior for documenting purpose of the collaborator in the test, of course this depends on the test and left at the judgment of the coder. – Brice Jul 02 '13 at 13:15
  • this still doesn't work. when i attempt `PowerMockito.verifyStatic(times(4))` it always passes, whether i say `times(0)`, `times(1)`, etc. – stantonk Feb 10 '16 at 00:15
  • @stantonk `verifyStatic` is not about stubbing but about verifying calls, if you have an example I may help you. – Brice Feb 10 '16 at 11:02
  • @Brice thanks i figured it out, the documentation wasn't clear that you had to invoke the expected call on the mocked static object. – stantonk Feb 12 '16 at 05:25
18

In simpler terms, Imagine if you want mock below line:

StaticClass.method();

then you write below lines of code to mock:

PowerMockito.mockStatic(StaticClass.class);
PowerMockito.doNothing().when(StaticClass.class);
StaticClass.method();
Vivek HJ
  • 201
  • 3
  • 6
  • 1
    Will it work for multiple methods of StaticClass.class, like StaticClass.method(); StaticClass.method1(); StaticClass.method2(); – S Kumar Jun 01 '18 at 10:22
7

To mock a static method that return void for e.g. Fileutils.forceMKdir(File file),

Sample code:

File file =PowerMockito.mock(File.class);
PowerMockito.doNothing().when(FileUtils.class,"forceMkdir",file);
duggu
  • 35,841
  • 11
  • 112
  • 110
Oshin Talreja
  • 101
  • 1
  • 2