Wednesday, April 28, 2010

PowerMock - Mocks on Steriods!

I have been developing software for some time now.  But have never seen a mocking/stubbing framework (in the java world) that is able to mock/stub everything!  literally everything!

People will argue that, the need to mock static methods, final classes/methods, mock static class, etc. is a sign of bad coding.  I couldn't agree more!  But time and again I have come to terms with a fact that there is a lot of legacy code people have already written and we are inevitably faced with situations where we have to work with it.  In such situations mocking framework like PowerMock is a real boon!

PowerMock basically extends other mocking libraries such as Mockito, EasyMocks and now even TestNGPowerMock uses a custom class-loader and byte-code manipulation to enable mocking of static methods, final classes/methods, etc.  Because of this, no changes need to be done to the IDE or continuous integration servers which simplifies adoption.

PowerMocks have the following capabilities

  • Extends various well known mocking frameworks like Mockito, EasyMocks and TestNG.  Hence, it has an extremely low learning curve if you are familiar with any of of those mocking libraries.
  • Can 
    • mock static methods
    • mock final methods
    • mock static classes
    • mock final classes
    • mock constructors
    • mock private methods
    • remove static initializes
    • partially mock a class i.e. create spy
    • Suppress methods
    • Suppress constructors
    • Suppress static initializes
    • Suppress fields!
    • On top of all this it can also mock/stub normal classes and interfaces :)
Wow! now that's what I call a mocking framework on steroids!

Well, if you like what you are reading and what to see some code in action, stay tuned in the next series of posts I will show working samples of how actually its done!

As usual, feedback, comments and complaints are always welcome!
Have some Fun!