Use Mockito to mock static void method

15,314 views
Skip to first unread message

Jeff S

unread,
Jun 3, 2009, 11:38:59 AM6/3/09
to PowerMock
I have a class like this:

public class StaticVoidMethodClass {
public static void toBeMocked(int someParam) {
// do some checks and throw RuntimeException if fail
}
}

I would like to stub out this static method behavior since I don't
care about the check & throw exception. I tried to do this using
Mockito (yes, we are using Mockito as our core mocking tool):

PowerMockito.mockStatic(StaticVoidMethodClass.class);
// in Mockito, there is a way of stubbing void :
// Mockito.doNothing().when(mockObj).toBeMocked(anyInt());

But how can I get the static instance (not really instance, but the
"static class". In the example, it's "mockObj") so I can use it in
doNothing().when(mockObj).toBeMocked(...)? If I am on the wrong
track, can anyone advise how this can be done?

Thanks,
Jeff


Jeff S

unread,
Jun 3, 2009, 1:38:51 PM6/3/09
to PowerMock
Never mind, I forgot to add the class name to @PrepareForTest. Once I
did that and call mockStatic(), the method call is stubbed with
nothing. For the record:

@PrepareForTest(StaticVoidMethodClass.class)
....

PowerMockito.mockStatic(StaticVoidMethodClass.class);

StaticVoidMethodClass.toBeMocked(123); // did nothing now


BTW, Powermock rocks!

-Jeff

Johan Haleby

unread,
Jun 4, 2009, 2:37:04 AM6/4/09
to powe...@googlegroups.com
Great that you sorted it out! I think one of the most difficult things when you're new to PowerMock is to remember the annotations. Hopefully you'll get used to it pretty quick though :). Thanks for your nice comments as well.

/Johan

Jeff S

unread,
Jun 8, 2009, 11:50:47 AM6/8/09
to PowerMock
Johan,

Yeah, I felt a lot more like 2nd nature now after written ton of
tests with powermock on past week.

Now I have a follow-on question. I would like to stub out a
static void method to throw an exception with Mockito. Can you shed
some light of how to do that?

@PrepareForTest(StaticVoidMethodClass.class)
....
PowerMockito.mockStatic(StaticVoidMethodClass.class);

// I would like the StaticVoidMethodClass.toBeMocked() method to throw
an exception
// in Mockito, I can do this:
// doThrow(testException).when(mockObj).toBeMocked(123);
// how can I do that in Powermock with Mockito?


Thanks a lot in advance!

-Jeff

Johan Haleby

unread,
Jun 9, 2009, 6:21:00 AM6/9/09
to powe...@googlegroups.com
Hi,

I'm not sure if it's possible for static void methods actually. We'll definitively look into this until the next release, improving the Mockito extension has the highest priority. But please let us know if you find a way to do it now as well.

/Johan

Jeff S

unread,
Jun 9, 2009, 9:46:31 AM6/9/09
to PowerMock
Johan,

Thanks for your reply. Besides lack of additional support for
Mockito, I think the current documentation is geared toward EasyMock
and it did take me some time to get it to work properly with Mockito.
For instance:

When I setup the expectation using PowerMockito.mockStatic(), I only
need to call mockStatic() once, but when I try to verify behavior, I
need to call verifyStatic() per method verification along with
Matchers on parameters, this is more of a mix with EasyMock semantic:

// only call mockStatic() once
PowerMockito.mockStatic(StaticClass.class);
Mockito.when(StaticClass.doSomething()).thenReturn(something);
Mockito.when(StaticClass.doMore(123)).thenReturn(more);
// more expectations

// execute test.....

// but when verifying result, I need to call verifyStatic() per method
expectation.
// Also, I can't use the Mockito.verify() semantic since it's static
method
PowerMockito.verifyStatic(StaticClass.class);
StaticClass.doSomething();
PowerMockito.verifyStatic(StaticClass.class); // call verifyStatic()
again
StaticClass.doMore(eq(123)); // with use of mockito matchers on
parameters

I really think Powermock is a great tool but things like this are
tricky but should easily be addressed by adding another wiki page
geared for Mockito. I also added a comment to Issue#103 on having
better documentation on Mockito.

Btw, I am willing to help to put up a wiki page for Mockito
support and of course you will have to proofread it. Just let me
know.

-Jeff

Johan Haleby

unread,
Jun 9, 2009, 12:01:34 PM6/9/09
to powe...@googlegroups.com
Hi,

I actually replied to issue #103, don't know if you saw it so I'll quote
it here:

"We would be extremely glad if you could help us out in any way so
you're more than welcome. The reason for the poor Mockito documentation
is that we haven't had enough time to produce it and also because the
Mockito support is kind of experimental. But for the 1.3 release Mockito
is a top priority and any help will be very much appreciated. I find it
strange that you need to use Mockito.eq though, I've never needed that
myself and you shouldn't need to I suppose [at least it's not the
intension] . There are some examples of Mockito usage in our SVN repo.
The first thing we probably should do is to link to those examples."

We're very much aware that we're EasyMock oriented right now and that's
something we'd like to change. The Mockito API extension is still in its
infancy today and was implemented to prove that PowerMock core and test
runners are decoupled from a specific mock framework (this was a huge
refactoring effort that took place for release 1.1).

If you have any suggestions on how we should solve a particular issue or
how the API should look like please just bring it up on the mailing-list
or add an issue so we can discuss it. And as I said previously we would
be extremely glad if you could help us out in any way, it would be very
nice of you if you're willing to help out with the documentation for
example. Of course you're also welcome to participate with the code if
you like.

/Johan

szczepiq

unread,
Jun 9, 2009, 1:26:36 PM6/9/09
to powe...@googlegroups.com
Hi powermockers!

Finally I've got some time to have a look how Mockito integration
works in powermock. I meant to do it earlier but had other stuff on my
mind (like releasing Mockito or... life =). I've got feedback/random
ideas, take whatever you like from it.

1. It would be nice if @PrepareForTest also did
PowerMockito.mockStatic(StaticClass.class); You could possibly check
in runtime what mocking framework is in use or just simply try doing
both PowerMock.mockStatic() & PowerMockito.mockStatic()
2. @PrepareForTest could have aliases or specific annotations:
@StaticallyMocked(StaticClass.class) or
@Unfinalized(FinalClass.class); That could make the test more
explicit.
3. I think I like the fact that I can put @PrepareForTest at the method level

I glanced at the implementation and it seems you have to depend on
loads of mockito internal code. Let me know about some ideas - I can
refactor some code so that your integration is easier.

Cheers,
Szczepan Faber
PS.
I'm still not with you on certain powermocking features but you will
allow me to have a different view on the mocking business, right? :-)

Johan Haleby

unread,
Jun 9, 2009, 3:37:42 PM6/9/09
to powe...@googlegroups.com
Hi,

Thanks for your feedback, much appreciated! I'll try to reply to your
comments.

1. I'm not sure if this is what we want. Of course it would probably be
possible to do but "PrepareForTest" does a lot more things right now
than just enabling static mocking (as you can probably guess) .
@PrepareForTest just tells PowerMock that a class should be modified to
allow for testability (or mockabilty even). This means that you can then
mock static methods of the class, suppress methods/constructors, create
a mock even if it's final etc etc. One of the key goals of PowerMock is
that people already familiar with a mock framework such as EasyMock or
Mockito should recognize the syntax and the structure of the "mock
setup" from these frameworks in a PowerMock extension API as well. Thus
it should be relatively simple to use PowerMock (at least that's our
goal), sort of what EasyMock class extensions is to plain EasyMock.
2. I think this is an interesting idea in general since it's very
explicit and it may give you a better "granularity" on what you want to
achieve in your test.
3. I like this too mainly because it gives you the benefit of knowing
exactly which classes that are prepared for test for a specific method.
The real down-side is that the implementation to get this working is
quite complex and hard to maintain. This is because each test annotated
with @PrepareForTest(..) is executed with a new junit runner and a new
class-loader. So under the hood several junit tests are actually
executed (each with its own classloader) and the end result is merged
back so that the user is not aware of this.

I'm glad to hear that you're willing to make life easier for us :). It's
been quite tricky to get the Mockito extension working. Without having
all the details in my head right now I believe that the reason why it
was a bit difficult to upgrade to Mockito 1.7 was that you did "new
CGLIBHacker().setMockitoNamingPolicy(methodProxy)" in
MethodInterceptorFilter#intercept(..) and then tried to look up some
fields using reflection. Unfortunately we had proxied the "methodProxy"
and thus the declared fields could not be found. So in this case it
would be nice if we somehow could supply our own implementation of the
CGLibHacker (or Mockito could make use of the powermock-reflect project
which traverses the hierarchy of an object when looking for fields :)).
But me and Jan will have to meet and discuss the current implementation
since it's likely to change and then perhaps we can come with some
suggestions that may make it easier for us if needed (and we'll see
whether you find them appropriate or not)? That would be excellent.

> I'm still not with you on certain powermocking features but you will allow me to have a different view on the mocking business, right? :-)

Of course but to be honest I actually think that we do share most things even though it may not be obvious :). Both me and Jan advocate the use of Mockito when we give talks nowadays for example and we stress that you should only use PowerMock when it's necessary and never misuse it (and we may of course have different opinions on that). But I still think that PowerMock serves a purpose, because not everyone is lucky enough to be working with new, perfectly-designed, "mock-friendly" code. But I still maintain that if the only reason you have for refactoring your code is to allow for "testability" then you shouldn't refactor (if it doesn't give you great benefits when it comes to understanding/maintaining the test-code). There must be other reasons than technical limitations (and there usually are).

/Johan

szczepiq

unread,
Jun 9, 2009, 4:55:14 PM6/9/09
to powe...@googlegroups.com
Hey,

>1. I'm not sure if this is what we want. Of course it would probably be
>possible to do but "PrepareForTest" does a lot more things right now
>than just enabling static mocking (as you can probably guess) .

That's what I thought. My thinking was that if prepareForTest() does
so much already why can't it prepare for static mocking as well. If
you prefer to keep separate api for static mocking an annotation would
be nicer I think, for example @StaticallyMocked. It's up to you,
though ;)

>was a bit difficult to upgrade to Mockito 1.7 was that you did "new
>CGLIBHacker().setMockitoNamingPolicy(methodProxy)" in

yeah... this was required to fix some very weird bug. I think the
easiest way is if I change the implementation so that it tries to set
this field on a parent as well. I'd prefer not to introduce yet
another dependency but thanks for the suggestion to use powermock for
it :)

Cheers,
Szczepan Faber

Jeff S

unread,
Jun 9, 2009, 10:09:06 PM6/9/09
to PowerMock
Johan,

Thanks. Let me take a look at the examples in SVN repo to see
what I can put together. Also, do you have a target date for 1.3
release? Just try to see if documenting current release makes sense
if 1.3 is coming up shortly (My guess is not that soon).

I will love to get my hand on the code as well but let me get more
comfortable on the code base first.

-Jeff

Johan Haleby

unread,
Jun 10, 2009, 2:23:35 AM6/10/09
to powe...@googlegroups.com
Hi,

That would be great!! I'll try to put together a wiki on how PowerMock works conceptually so that you can have a look at it and hopefully it'll get a bit easier to get into. I've already written a little bit about how it works at http://blog.jayway.com/2009/05/17/mocking-static-methods-in-java-system-classes/.

I'm not sure when the 1.3 release will be available but I guess not in the imminent future. In the mean time it would be execellent with a basic wiki page though. The examples that I refered to are located under http://code.google.com/p/powermock/source/browse/trunk/modules/module-test/powermockito/junit4/src/test/java/samples/powermockito/junit4/ in subversion. They are actually our own tests to make sure that the functionality works so they don't really suite as good documentation examples, but I guess it's better than nothing.

/Johan

Johan Haleby

unread,
Jun 10, 2009, 2:31:39 AM6/10/09
to powe...@googlegroups.com
Hi,


> yeah... this was required to fix some very weird bug. I think the easiest way is if I change the implementation so that it tries to set this field on a parent as well. I'd prefer not to introduce yet another dependency but thanks for the suggestion to use powermock for it :)

Hehe actually powermock-reflect is a separate project so it's not dependent on core or any other stuff. But I guess your change will be good enough for us as for now. But I'll get back to you when we've had a new look at the current implementation. Thanks for your help.

/Johan

Jeff Szeto

unread,
Jun 15, 2009, 12:13:26 PM6/15/09
to powe...@googlegroups.com

Johan,

I put together a wiki (attached) for Mockito with Powermock.  So far I only had section for static method and partial mock but would like your feedback on it.  I tried to make it concise and get-to-point with examples without fluffy stuff since it's a wiki page.

BTW, what's the best way for me to publish things like that to powermock project?  I wrote this page in Google Docs.

Thanks,
Jeff
Using_PowerMock_with_Mo.html

Johan Haleby

unread,
Jun 15, 2009, 4:50:24 PM6/15/09
to powe...@googlegroups.com
Thank you very much! I converted it to google code wiki format and put
it up on the webpage now.

/Johan
> <mailto:johan.hal...@gmail.com>> wrote:
> >
> > >>>> Great that you sorted it out! I think one of the most
> difficult things
> >
> > >>> when
> >
> > >>>> you're new to PowerMock is to remember the annotations.
> Hopefully you'll
> >
> > >>> get
> >
> > >>>> used to it pretty quick though :). Thanks for your nice
> comments as well.
> >
> > >>>> /Johan
> >
> > >>>> On Wed, Jun 3, 2009 at 7:38 PM, Jeff S
> <szetoj...@gmail.com <mailto:szetoj...@gmail.com>> wrote:
> >
> > >>>>> Never mind, I forgot to add the class name to
> @PrepareForTest. Once I
> > >>>>> did that and call mockStatic(), the method call is
> stubbed with
> > >>>>> nothing. For the record:
> >
> > >>>>> @PrepareForTest(StaticVoidMethodClass.class)
> > >>>>> ....
> >
> > >>>>> PowerMockito.mockStatic(StaticVoidMethodClass.class);
> >
> > >>>>> StaticVoidMethodClass.toBeMocked(123); // did nothing now
> >
> > >>>>> BTW, Powermock rocks!
> >
> > >>>>> -Jeff
> >
> > >>>>> On Jun 3, 11:38 am, Jeff S <szetoj...@gmail.com
> ------------------------------------------------------------------------
>
>
> Using PowerMock with Mockito
>
> Basically, PowerMock provides a class called "PowerMockito" for
> creating mock object/class and initiating verification, everything
> else you can still use Mockito to setup and verify expectation (e.g.
> when(), times(), anyInt()).
>
> All usages require @RunWith(PowerMockRunner.class) and
> @PrepareForTest() annotated at class level.
>
>
> Mocking Static Method
>
>
> How to mock and stub:
>
> 1. Add @PrepareForTest() at class level.
> @PrepareForTest(Static.class); // Static.class contains static
> methods
>
> 1. Call PowerMockito.mockStatic() to mock a static class (use
> PoweMockito.mockStaticPartial(class, method) to mock a specific method):
> PowerMockito.mockStatic(Static.class);
>
> 2. Just use Mockito.when() to setup your expectation:
> Mockito.when(Static.firstStaticMethod(param)).thenReturn(value);
>
>
> How to verify behavior:
>
> 1. Call PowerMockito.verifyStatic() to start verifying behavior
> (Important: You need to call verifyStatic() *per method verification*):
> PowerMockito.verifyStatic(Static.class);
>
> 2. Use EasyMock-like semantic to verify behavior:
> Static.firstStaticMethod(param);
>
>
> How to argument matchers:
>
> Mockito argument matchers are still applied to PowerMock'ed mock. For
> example, using custom argument matchers per mocked static method:
>
> PowerMockito.verifyStatic(Static.class);
> Static.thirdStaticMethod(*Mockito.anyInt()*);
>
>
> How to verify exact number of calls:
>
> You can still use Mockito.VerificationMode (e.g Mockito.times(x)) with
> PowerMockito.verifyStatic():
>
> PowerMockito.verifyStatic(Static.class, Mockito.times(1));
>
>
> How to stub void static method to throw exception:
>
> This is not yet supported in current release 1.2.
>
>
> *A full example for mocking, stubbing & verifying static method:*
>
> @RunWith(PowerMockRunner.class)
> @PrepareForTest(Static.class)
> public class YourTestCase {
> @Test
> public void testMethodThatCallsStaticMethod() {
> // mock all the static methods in a class called "Static"
> PowerMockito.mockStatic(Static.class);
> // use Mockito to set up your expectation
> Mockito.when(Static.firstStaticMethod(param)).thenReturn(value);
> Mockito.when(Static.secondStaticMethod()).thenReturn(123);
>
> // execute your test
> classCallStaticMethodObj.execute();
>
> // Different from Mockito, always use
> PowerMockito.verifyStatic() first
> PowerMockito.verifyStatic(Static.class, Mockito.times(2));
> // Use EasyMock-like verification semantic per static method
> invocation
> Static.firstStaticMethod(param);
>
> // Remember to call verifyStatic() again
> PowerMockito.verifyStatic(Static.class); // default is once
> Static.secondStaticMethod();
>
> // Again, remember to call verifyStatic()
> PowerMockito.verifyStatic(Static.class, Mockito.never());
> Static.thirdStaticMethod();
> }
> }
>
>
> Partial Mocking
>
> You can use PowerMock to partially mock a method which must be
> non-final.
>
> *How to mock and stub:*
> 1. Use PowerMockito.mockPartial(): (You can also use Annotation
> @Mock("methodToMock") or PowerMockito.mock() for a method with
> specific parameters)
> PartialMockClass mockObj =
> PowerMockito.mockPartial(PartialMockClass.class, "methodToMock");
>
> 2. Just use Mockito.when() to setup expectation:
> Mockito.when(mockObj.methodToMock()).thenReturn(123);
>
> *How to verify behavior:*
>
> Just use Mockito.vertify() for verification:
> Mockito.verify(mockObj, times(2)).methodToMock();
>
>
> How to argument matchers:
>
> Mockito argument matchers are still applied to PowerMock'ed mock:
> Mockito.verify(mockObj).methodToMockToo(*Mockito.anyInt()*);
>
>
> How to stub void static method to throw exception:
>
> Just use Mockito semantic of setting up void method stub:
> Mockito.doThrow(new
> RuntimeException("TEST")).when(mockObj).methodToMock();
>
>
> A full example of partial mocking:
>
> @RunWith(PowerMockRunner.class)
> @PrepareForTest(PartialMockClass.class)
> public class YourTestCase {
> @Test
> public void testPartialMock() {
> // create a partially mocked object for method "methodToMock"
> PartialMockClass mockObj =
> PowerMockito.mockPartial(PartialMockClass.class, "methodToMock");
> // use Mockito to set up your expectation
> Mockito.when(mockObj.methodToMock()).thenReturn(value);
>
> // execute your test
> classCallPartialMockObj.execute();
>
> // Use Mockito.verify() to verify result
> Mockito.verify(mockObj, times(2)).methodToMock();
> }
> }
>

Jeff S

unread,
Jun 16, 2009, 11:07:48 AM6/16/09
to PowerMock
Johan,

I also would like to add more sections to this wiki page, would it
be possible to add me as your project member? I am also reading up
the source code too and hopefully I can contribute down the road as
well.

Thanks,
Jeff

On Jun 15, 4:50 pm, Johan Haleby <johan.hal...@gmail.com> wrote:
> Thank you very much! I converted it to google code wiki format and put
> it up on the webpage now.
>
> /Johan
>
>
>
> Jeff Szeto wrote:
>
> > Johan,
>
> > I put together a wiki (attached) for Mockito with Powermock.  So far I
> > only had section for static method and partial mock but would like
> > your feedback on it.  I tried to make it concise and get-to-point with
> > examples without fluffy stuff since it's a wiki page.
>
> > BTW, what's the best way for me to publish things like that to
> > powermock project?  I wrote this page in Google Docs.
>
> > Thanks,
> > Jeff
>
> > On Wed, Jun 10, 2009 at 2:23 AM, Johan Haleby <johan.hal...@gmail.com
> > <mailto:johan.hal...@gmail.com>> wrote:
>
> >     Hi,
>
> >     That would be great!! I'll try to put together a wiki on how
> >     PowerMock works conceptually so that you can have a look at it and
> >     hopefully it'll get a bit easier to get into. I've already written
> >     a little bit about how it works at
> >    http://blog.jayway.com/2009/05/17/mocking-static-methods-in-java-syst....
>
> >     I'm not sure when the 1.3 release will be available but I guess
> >     not in the imminent future. In the mean time it would be
> >     execellent with a basic wiki page though. The examples that I
> >     refered to are located under
> >    http://code.google.com/p/powermock/source/browse/trunk/modules/module...
> >     in subversion. They are actually our own tests to make sure that
> >     the functionality works so they don't really suite as good
> >     documentation examples, but I guess it's better than nothing.
>
> >     /Johan
>
> >     On Wed, Jun 10, 2009 at 4:09 AM, Jeff S <szetoj...@gmail.com
> ...
>
> read more »

Johan Haleby

unread,
Jun 16, 2009, 12:50:02 PM6/16/09
to powe...@googlegroups.com
I understand. Let me get back to you in a little while. We're very glad
that you want to help out!
Reply all
Reply to author
Forward
0 new messages