This blog will share my understanding about EasyMock, before moving forward to EasyMock first want to tell you about what is Mock and what is Mock Object and there purpose.
One of the web definition of Mock is “An intimation of counterfeit”. If we apply definition of mock to mock objects, mock objects are just an intimation or counterfeit of objects. Now we have to look where these mock objects are applied in real world.
Consider a use case where we have a UserService that performs some business operation on a User entity and then persists user entity using UserDao(Persistence Service). When we write test case for UserService, unintentionally we will be testing UserDao also and we have to take care of successful execution of UserDao also. In such cases Mock Objects comes into picture, we create a mock object of UserDao and provide this mock object to UserService. UserDao mock object will intimate as UserDao and will behave as required.
In coming sections I'll be taking this use case as an example
EasyMock is about creating mock objects for interfaces. The mock objects are created using java proxy mechanism. Once mock objects are created you have to record the behavior of mock objects before using mock objects. Recording behavior of mock objects signifies registering method calls to mock object which can be invoked while testing.
Before using a mock object it needs to be instantiated. To instantiate a mock object first it needs to created using createMock(EasyMock.createMock(
userDao = EasyMock.createMock(UserDao.class);
This section tells you about adding behavior for method call to mock objects. As told in previous section behaviors to a mock object are added in record sate. Adding behavior for method call is similar to actually calling the method, the only difference is that at the time of recording behavior gets registered to mock object. If we have to record the delete operation of user entity we have to write userDao.delete(user) in the record phase of userDao.
So if we have to record the persistence behaviour to mock “userDao” object the code code will be like this// Setting up the expected value of the method call delete
userDao.delete(dummyUser);
// Setup is finished need to activate the mock userDao object
EasyMock.replay(userDao);
In next blog I'll discuss behavior of mock objects in replay phase and the advanced features of easy mock such as restricting no of times a method can be called, ensuring the sequence of method calls, verifying the return values etc.
So keep waiting :)