Saturday, November 8, 2008

Mock your world

I have been always fascinated by this neat idea of mocking in the context of the testing world. So as a topic for this post, i thought writing about this concept may give it more clarity and strength in my mind and hopefully it will do the same for the community.
Definition:
Mocking is replacing all the collaborators and dependencies of the class under test by mocks or fake objects so you can easily and efficiently unit test it. Why do you need Mocking for?
  • It gives you the ability to focus your test on the functionality of a code unit.
  • It removes your dependency on the different components of your app, such as database...
  • It makes your tests run faster.
  • It allows you to have a clean and better design (interface driven design).
Some tips on the implementation: In order to make mocking an easy task, you need to take in consideration the following factors:
  • Base your design on interfaces instead of inheriting from a class, because of the fact that classes may sometimes be final or have static or final methods and therefore will not allow you to override them.
    In the diagram above, we used the interface implemented by one of the collaborators of the class under test to create our mock.
    As showed in the diagram above, we tried to mock User by extending it, but since it has the method findAllUsers() marked as final we could not override it, which means that the mocking operation was a failure.
  • make your objects as small as possible so you can easily mock them (divide and conquer principle).
  • remove the instantiation of the collaborators from within the class under test so you can mock them.
Projects: If you don't like creating mocks manually, here are some open source projects that can help you do that:
  • http://www.jmock.org
  • http://www.easymock.org
  • http://code.google.com/p/mockito
Please don't hesitate to enrich this post by your comments.

No comments: