Thursday, July 9, 2009

JUnit with EasyMock

Ever wondered how could you test your classes without waiting for your colleague to complete his classes.. I think EasyMock is one of the answers..

EasyMock helps to create mock objects by passing an interface as argument. It is very helpful when you have complex web application that involves lot of custom objects and you want to test a particular class which is dependent on ten other classes.

It has 2 simple steps to follow.

1. Create mock objects
2. Set the expected values in mock object so that the methods of the object return the same values

It is very easy to use. (Steps below:-)

1. Add easymock libraries
2. Create JUnit test case
3. Create mock objects using EasyMock.createStrictMock(MyInterface.class)
4. Set expected values using EasyMock.expect(myObj.myMethod()).andReturn("ReturnvaluefromMyMethod").
This statement means that when myMethod() is invoked, return the value "ReturnvaluefromMyMethod". In essence, whichever method you are planning to invoke later, set the values expected to be returned from the method.
5. call EasyMock.replay(myObj);

Our mock objects are ready to use.

1. Do not call any methods of the mock object until you call replay(). Otherwise it will throw an IllegalStateException at that point.

2. If your interface contains getter/setter methods, instruct the getter() [not the setter()] with the expected return values. In general, we are used to invoke the setter method with the value to be set and use the getter methods to retrieve the value.

Hope it helps!

No comments:

Post a Comment