Turbocharge Your Mocking Framework With PowerMock
As mentioned in my last post, I am an ardent fan of the Mockito Framework. Originally developed as a fork of EasyMock, it equips developers with the tools to create mock objects using clean and expressive code. In this post, we will show how PowerMock can be used alongside Mockito (or EasyMock) to create mocks for classes that appear at first ‘unmockable’. Suppose we have the following class:
…which has a dependency on a DataProvider:
If we are to write a unit test for the ResultsWriter class, then we will need to mock the DataProvider, to avoid depending on a file in the filesystem. However, it is not always viable to refactor production code to make it more testable, and since the DataProvider class is final, we cannot directly mock it with Mockito or EasyMock.
This is where PowerMock comes into play. With features to mock (or partially mock) final classes, static methods, and private methods, we have the tools at our disposal to test whatever the codebase may throw at us. A unit test for the ResultsWriter class, using a partial mock of the DataProvider is given below:
In the above example, we have barely scratched the surface of what PowerMock is capable of. Explore more ways to turbocharge your favourite mocking framework at http://code.google.com/p/powermock/.