Easymock helps you to realize isolated tests of your business logic. The idea of mock based tests is to mock all dependent objects and to inject expected behaviour. The following example describes how to use basically EasyMock.
Task description:
You have to develop a class, which multiply a product price with an amount. After that you have to subtract the reduction. The multiplication logic should be realized by an external MultiplicationService class. The subtraction will be implemented by your code.
package org.developers.blog.easymockexample;
public class CalculationManager {
private IMultiplicationService multiplicatorService;
public IMultiplicationService getMultiplicatorService() {
return multiplicatorService;
}
public void setMultiplicatorService(IMultiplicationService multiplicatorService) {
this.multiplicatorService = multiplicatorService;
}
public Integer calculatePrice(Integer price, Integer amount, Integer reduction) {
return multiplicatorService.multiply(price, amount) - reduction;
}
}
package org.developers.blog.easymockexample;
/**
*
* @author rafsob
*/
public interface IMultiplicationService {
public Integer multiply(Integer number1, Integer number2);
}
package org.developers.blog.easymockexample;
import org.easymock.*;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
*
* @author rafsob
*/
public class EasyMockTest {
private IMultiplicationService multiplicatorServiceMock;
private CalculationManager calculationManager;
@Before
public void setUp() throws Exception {
multiplicatorServiceMock = EasyMock.createMock(IMultiplicationService.class);
calculationManager = new CalculationManager();
calculationManager.setMultiplicatorService(multiplicatorServiceMock);
}
@Test
public void testCalculationManager() {
Integer oneProductPrice = 12;
Integer amount = 3;
Integer reduction = 6;
//inject behaviour of MultiplicatorService
EasyMock.expect(multiplicatorServiceMock
.multiply(oneProductPrice, amount))
.andReturn(oneProductPrice * amount);
//setting up the mock
EasyMock.replay(multiplicatorServiceMock);
//object to be tested
Integer result =
calculationManager.calculatePrice(oneProductPrice, amount, reduction);
Assert.assertEquals(result, oneProductPrice * amount - reduction);
EasyMock.verify(multiplicatorServiceMock);
}
}
You can download the easymock example as Maven project here.
RegardsRafael Sobek
