1. Introduction
The mock objects allows to make unit tests on objects depending on other objects. We will replace this dependencies with mock objects. With that, we can by example verify than the method xyzzy() has been called 5 times and returned 33. That can be practical in a several cases. By exampe, if the object to mock is slow or undeterministic (depending on time, or why not on the weather). This objects are really difficult to test because we can make a lot of tests but we could never find the special cases. Test cases with mock objects enable us to test this cases.
There is several tools to make mock objects. In this article, we will use EasyMock 2.5.2 with JUnit 4.7.
Here is the interface to test :
public interface ISimpleDao { void save(String title); void remove(String title) throws NotExistingException; int count(); void debug(); boolean isValid(String title); void insert(String title); }
And here is our class to test :
public class SimpleService { private ISimpleDao dao; public void setDao(ISimpleDao dao){ this.dao = dao; } public void insert(String title){ if(dao.isValid(title)){ dao.insert(title); } } public void save(String... titles){ for(String title : titles){ dao.save(title); } } public boolean remove(String title){ try { dao.remove(title); } catch (NotExistingException e){ return false; } return true; } public int size(){ return dao.count(); } public void debug(){ System.out.println("Debug informations of SimpleService"); dao.debug(); } }
Our mock will implement the ISimpleDao interface and we will give it to SimpleService who’s the class to test. This example is really simplistic, but it will be enough to cover the main features of EasyMock.

Pingback: JUnit: Automatically Managing Mocks « Ted Young