Monday, May 10, 2010

How to mock final methods and classes using PowerMock

This is the second post in the how-to series of using PowerMockito to write beautiful unit-tests. In my previous post we saw how can we write unit-tests for mocking static methods.

Today, I will demostrate how we can mock final class and final methods using PowerMocks (Mockito api) - Mocks on steroids!


I am going to take a ficticious example, were AnotherService class's invokeFinal() method invokes a final method on the instance of FinalService class which is a final class.

Code under test:

The final method doSomething in the final Class FinalService does nothing, just throws an exception.  AnotherService's invokeFinalMethod invokes doSomething method.

Most common mocking framework in the java world cannot mock final classes/methods because they are typically based on creating proxies.  Creating proxies for final classes is not possible as we cannot subclass a final classes.

So how we do we it in PowerMocks (Mockito api)?

How will we test it - How do they do it!:

Aha! Its tad simple.  We don't need to do anything special here.

We have to use @PrepareForTest annotation with FinalService so that PowerMocks can actually mock FinalService (Go Here for explanation on @PrepareForTest).  Next up, we need to create the stub of FinalService using the following code

Then, we have two approaches

I will show both the approaches

State based testing:

Interaction based testing:

Thats it!

It is needless to say that things look pretty easy with PowerMocks (Mockito api).  They look easy because they are easy with PowerMocks!  Yes! you can with PowerMocks (Mockito api)!

Feedback, questions and comments are always welcome.
Have some Fun!