Unit testing is important and a developer has to create unit test code to automate the unit testing process. But it is always that the code the developer has written is dependent on code that would be written by some other developer. When that code is not be ready yet, it will be difficult for developer 1 to write his/her unit test code. To make it simple, lets say developer 1 develops code for class A and class A is dependent on class B. Class B has to be done by another developer or let’s say that the design is not ready yet to write code for class B.
So how does developer 1 create his unit tests when the dependent class is not ready? The answer is to mock the code B. The mock object is a dumb object having same method and field signatures but with a different class/program name (example BMock) and the methods always return back a static output. The mock object is a temporary object to fool the test case of object A that the functionality dependency will be met by the class BMock. Once the actual class B is ready, it is just a matter of replacing the BMock declaration and instantiation to B. Now this process can even be made simpler when coding to an interface. The Mock object is an implementation of the same interface that the actual implementation would implement. In this case the changes necessary after the original implementation is available will be minimal.
Mocking frameworks help in creating mock objects to reduce the additional effort required to create these classes. There are several mock frameworks. Some of them listed below.
- EasyMock - Generates mock objects for interfaces on the fly
- JMock - Lightweight framework that can be extended and configured
- rMock - Another framework for Java that can be used with JUnit
- EasyMock.net - EasyMock for the .Net environment
- MockR - Mock for Ruby
To kick start with EasyMock, here is a good article “Getting started with EasyMock“.