About Ram Mokkapaty

Ram holds a master's degree in Machine Design from IT B.H.U. His expertise lies in test driven development and re-factoring. He is passionate about open source technologies and actively blogs on various java and open-source technologies like spring. He works as a principal Engineer in the logistics domain.

Powermock – Mockito Integration Example

Most of the mocking frameworks in Java, including Mockito, cannot mock static methods or final classes. If we come across a situation where we need to test these components, we won’t be able to unless we re-factor the code and make them testable. For example:

Making private methods packaged or protected

Avoiding static methods

But re-factoring at the cost of good design may not always be the right solution.
In such scenarios, it makes sense to use a testing framework like Powermock which allows us to mock even the static, final and private methods.
Good thing about Powermock is that it doesn’t re-invent the testing framework and in fact enhances the testing frameworks like Easymock and Mockito.

In this article, we will see an integration example of Powermock and Mockito but first let’s do the setup.

2. System Under Test (SUT)

Our system under test is a system called SomeSystem which owns some services. A service is defined by Service interface which has couple of methods getName() and start(). If the start of the service is successful it will return 1 else 0.

One can add a Service to the SomeSystem using add(service) method. Our SubSystem has a start() method which will start the services it contains. On start of each service, ServiceListener is notified of the success or failure of the service.

3. Integrate PowerMockito and Mockito

In setupMock(), we will set up our system. We will create mock objects for Service and ServiceListener using Mockito.mock. Both are interfaces and we don’t have the actual implementations ready. Since SomeSystem is our SUT, we will create a spy object of it so that later we can stub some of its behavior.

Now let’s come to our first test startSystem:

We will stub service.start() using PowerMockito so that it returns 1.

Next, we start the system calling system.start()

Finally, we will verify the behavior using Mockito’s verify() API

Mockito.verify(serviceListener).onSuccess(service);

Notice that we stub using PowerMockito but verify using Mockito. This shows that Powermock doesn’t re-invent the wheel rather enhances the existing testing frameworks.

Stub using PowerMockito. service.start() should return 1 as we want start of the service to be successful
Start the system, should start the services in turn
Verify using Mockito that service started successfuly
Verifed. Service started successfully

4. Mocking Static Method

The use of static methods goes against the Object Oriented concepts but in real world we still use a lot of static methods and there are times when it makes sense to use static methods. Nevertheless, the ability to mock static methods may come handy to us. In this example, we will stub a static non-void method.

In the beginning of test class you will notice @RunWith annotation that contains PowerMockRunner.class as value. This statement tells JUnit to execute the test using PowerMockRunner.

You may also see annotation @PrepareForTest which takes the class to be mocked. This is required when we want to mock final classes or methods which either final, private, static or native.

We will use PowerMockito.mockStatic statement which takes in the class to be mocked. It tells PowerMockito to mock all the static methods. We then stub the static method’s behavior.

For example, in stubStaticNonVoidMethod, we stub SomeSystem.startServiceStaticWay to return 1.

Call mockStatic SomeSystem.class to enable static mocking
Stub static method startServiceStaticWay to return 1
Start the system, should start the services in turn
Verify using Mockito that service started successfuly
Stub static method startServiceStaticWay to return 0
Start the system again
Verify using Mockito that service has failed

5. Mocking static void Method

In this example, we will mock a void static method. The first step would be to call PowerMockito.mockStatic similar to the static non-void method. Since a void method doesn’t return anything, the earlier way of mocking static methods won’t work here.

PowerMockito.doNothing().when(SomeSystem.class);

Next, we will stub the behavior. After stubbing, we will call the static method on which it applies.

Call mockStatic SomeSystem.class to enable static mocking
Stub static void method SomeSystem.notifyServiceListener to do nothing
Stub using PowerMockito. service.start() should return 1 as we want start of the service to be successful
Start the system
Verify static method startServiceStaticWay(service) is called
Verify serviceListener.onSuccess(service) is not called as notifyServiceListener is stubbed to do nothing

6. Subbing Private Method

Using PowerMockito we can stub as well as verify private methods. In this example, I will show you how to stub a private method.

Our private method addEvent adds an event to the list. The event will tell us know whether a service started successfully or failed. Since we can’t access the private method, we will have to pass the SUT object, private method name along with the method arguments to PowerMockito.doNothing().when() method.

In test case stubPrivateMethodAddEvent, we stub addEvent to do nothing.

PowerMockito.doNothing().when(system, "addEvent", service, true)

In test case stubPrivateMethodGetEventString, we stub getEvent to return some hardcoded string.

In stubPrivateMethodAddEvent, since we have stubbed addEvent to do nothing, no events will added to the list.

In stubPrivateMethodGetEventString, we confirm that the event string we have returned is found in the events.

Output:

Test stubPrivateMethodAddEvent:
Stub using PowerMockito. service.start() should return 1 as we want start of the service to be successful
Stub service name to return serviceA
Stub private addEvent to do nothing
Start the system, should start the services in turn
Since we have stubbed addEvent, assert that system.getEvents() is empty
Test stubPrivateMethodGetEventString:
Stub using PowerMockito. service.start() should return 1 as we want start of the service to be successful
Stub service name to return serviceA
Stub private addEvent to do nothing
Start the system, should start the services in turn
Since we have stubbed getEvent, assert that system.getEvents() contains the event string
[serviceA is successful]

7. Verifying Private Method

Verification is similar to stubbing and PowerMockito allows us to verify even the private methods. The name of the method is passed to the PowerMockito.verifyPrivate along with its arguments.

Stub using PowerMockito. service.start() should return 1 as we want start of the service to be successful
Stub service name to return serviceA
Start the system, should start the services in turn
Verify private method addEvent(service, true) is called
Verified private method is called

Newsletter

Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

Email address:

Receive Java & Developer job alerts in your Area

Leave this field empty if you're human:

Join Us

With 1,240,600 monthly unique visitors and over 500 authors we are placed among the top Java related sites around. Constantly being on the lookout for partners; we encourage you to join us. So If you have a blog with unique and interesting content then you should check out our JCG partners program. You can also be a guest writer for Java Code Geeks and hone your writing skills!

Disclaimer

All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners. Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries. Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.