My favorites | Sign in
Project Logo
                
Search
for
Updated Dec 16, 2009 by johan.haleby
MockitoUsage13  

Using PowerMock with Mockito

Note: PowerMock 1.3.5 only works with Mockito 1.8.1 & 1.8.2. PowerMock 1.3 only works with Mockito 1.8. PowerMock 1.2.5 works with 1.7

Basically, PowerMock provides a class called "PowerMockito" for creating mock/object/class and initiating verification, and expecations, everything else you can still use Mockito to setup and verify expectation (e.g. 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.
  2.    @PrepareForTest(Static.class); // Static.class contains static methods
  3. Call PowerMockito.mockStatic() to mock a static class (use PoweMockito.spyStatic(class) to mock a specific method):
  4.         PowerMockito.mockStatic(Static.class);
  5. Just use Mockito.when() to setup your expectation:
  6.         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):
  2.         PowerMockito.verifyStatic();
  3. Use EasyMock-like semantic to verify behavior:
  4.         Static.firstStaticMethod(param);

How to use argument matchers

Mockito matchers are may still applied to a PowerMock 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(Mockito.times(2)):

PowerMockito.verifyStatic(Mockito.times(1));

How to stub void static method to throw exception

If not private do:

PowerMockito.doThrow(new ArrayStoreException("Mock error")).when(StaticService.class);
StaticService.executeMethod();

Note that you can do the same for final classes/methods:

PowerMockito.doThrow(new ArrayStoreException("Mock error")).when(myFinalMock).myFinalMethod();

For private methods use PowerMockito.when, e.g.:

when(tested, "methodToExpect", argument).thenReturn(myReturnValue);

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(Mockito.times(2));
        // Use EasyMock-like verification semantic per static method invocation
        Static.firstStaticMethod(param);

        // Remember to call verifyStatic() again
        PowerMockito.verifyStatic(); // default times is once
        Static.secondStaticMethod();

        // Again, remember to call verifyStatic()
        PowerMockito.verifyStatic(Mockito.never());
        Static.thirdStaticMethod();
    }
}

Partial Mocking

You can use PowerMockito to partially mock a method using PowerMockito.spy or PowerMockito.spyStatic.

How to verify behavior

Just use Mockito.vertify() for standard verification:

    Mockito.verify(mockObj, times(2)).methodToMock();

How to verify private behavior

Use PowerMockito.verifyPrivate(), e.g.

    verifyPrivate(tested).invoke("privateMethodName", argument1);

This also works for private static methods.

How to mock construction of new objects

Use PowerMockito.whenNew, e.g.

  whenNew(MyClass.class).withNoArguments().thenThrow(new IOException("error message"));

Note that you must prepare the class creating the new instance of MyClass for test, not the MyClass itself. E.g. if the class doing new MyClass() is called X then you'd have to do @PrepareForTest(X.class) in order for whenNew to work.

How to verify construction of new objects

Use PowerMockito.verifyNew, e.g.

   verifyNew(MyClass.class).withNoArguments();

How to argument matchers

Mockito matchers are may still applied to a PowerMock mock:

    Mockito.verify(mockObj).methodToMockToo(Mockito.anyInt());  

A full example of partial mocking

@RunWith(PowerMockRunner.class)
@PrepareForTest(PartialMockClass.class)
public class YourTestCase {
    @Test
    public void testPartialMock() {        
        PartialMockClass mockObj = PowerMockito.spy(new PartialMockClass());
        ClassUnderTest classUnderTest = new ClassUnderTest(mockObj);

        // use Mockito to set up your expectation
        Mockito.when(mockObj.methodToMock()).thenReturn(value);

        // execute your test
        classUnderTest.execute();

        // Use Mockito.verify() to verify result
        Mockito.verify(mockObj, times(2)).methodToMock();
    }
}

Further information

Have a look at the source in subversion for examples. Also read the PowerMockito related blog at the Jayway team blog.


Comment by rakmoh, Oct 09, 2009

Example for the partial mocking doesn't seem right. Check the javadoc for the spy method, it returns void (instead of PartialMockClass? as shown in this example).

Comment by johan.haleby, Oct 10, 2009

Well there are two spy methods, one that takes a class and on that takes T. The one that takes class should only be used when spying on static methods, the other one for instance methods. I.e. you must create an instance of the object before calling spy!

Comment by rakmoh, Oct 13, 2009

I agree that there are two spy methods. However, in this example the spy method takes a class and returns mockObj which is wrong. As per the javadoc this method should return void: http://powermock.googlecode.com/svn/docs/powermock-1.3/apidocs/index.html

Comment by johan.haleby, Oct 14, 2009

Oh now I understand what you mean! Sorry I'll fix the documentation (it was made in a hurry). Thanks!


Sign in to add a comment
Hosted by Google Code