Since the advent of dependency injection (DI) as a staple of enterprise development using tools such as Spring or Guice, your code has become a lot easier to test. You no longer need to code up voodoo such as plugging in dummy resource locators or the like based on some random environment variable to tell your code to switch into “test mode”. Everything is a POJO with interfaces as dependencies rather than classes, which means that it can be easily tested as a POJO. Nevertheless, it still surprises me as to how many people don’t know how to do this. Perhaps it is the perception that you need to have a running back end to test a service tier, or that you need the rest of the system to test a web front end. Not so.
Enter the mock object. According to Wikipedia – “mock objects are simulated objects that mimic the behavior of real objects in controlled ways”. And thanks to freely available Java toolkits such as EasyMock and jMock, making them available to your tests is as easy as plugin in a Jar file into your IDE. I’m a heavy user of EasyMock, so what follows is a simplified example of a jUnit test testing the middle tier of your typical DI-based application.
The following example deals with the following classes:
- WorkItem – a simple value object
- WorkItemException – an exception
- WorkItemService – an interface of a middle tier class
- WorkItemDao – an interface to the data layer of our application. This is what we are going to mock up.
- WorkItemServiceImpl – an implementation of that class. This is what we are going to test.
- WorkItemServiceImplTest – our test class
First, let’s get the uninteresting classes out of the way. Our WorkItem is just a bean that gets passed between the layers:
package jkorab.example.mock; public class WorkItem { int workItemNo; public int getWorkItemNo() { return workItemNo; } public void setWorkItemNo(int workItemNo) { this.workItemNo = workItemNo; } }
The WorkItemException is an exception that gets thrown:
package jkorab.example.mock; public class WorkItemException extends Exception { private static final long serialVersionUID = 1L; }
Now we come to the class that normally sits in the business tier of our application:
package jkorab.example.mock; public interface WorkItemService { /** * Trivial method. Given a workItem number > 0, returns a workItem instance. * Used to show how you might test the wrapping of an exception. * * @return WorkItem or null. */ public abstract WorkItem generateWorkItem(int workItemNo); }
Let’s take a look at the interface of the class it uses to do its work:
package jkorab.example.mock; public interface WorkItemDao { /** * Given a workItem number > 0, returns a workItem instance. * @param workItemNo workItem number * @return WorkItem if workItemNo > 0. * @throws WorkItemException if workItemNo <= 0. */ public WorkItem getWorkItem(int workItemNo) throws WorkItemException; }
Our example is, as is the spirit of most tutorials, pretty contrived. The top tier of our application wants to load a WorkItem, so it passes a work item number to the service tier. The service tier gets the work item, and if it cannot find it, returns null. The DAO on the other hand, gets a work item number and it the number is less than or equal to 0, it throws an exception, otherwise it loads the WorkItem.
Here’s the implementation of the WorkItemService:
package jkorab.example.mock; public class WorkItemServiceImpl implements WorkItemService { private WorkItemDao workItemDao; public void setWorkItemDao(WorkItemDao workItemDao) { this.workItemDao = workItemDao; } /* (non-Javadoc) * @see jkorab.example.mock.WorkItemService#generateWorkItem(int) */ public WorkItem generateWorkItem(int workItemNo) { WorkItem workItem = null; try { workItem = workItemDao.getWorkItem(workItemNo); } catch (WorkItemException workItemException) { // log and continue. we'll return null. } return workItem; } }
The class here is doing what the interface “said on the tin”. In addition it has a setter so that the DI container can supply it with a DAO implementation. That’s where our hook is that will enable us to test the service without an actual DAO implementation.
The first thing we need in order to write a test class is a mock DAO. This is the component that the service class will call. In addition we will also need a mock control. Think of this as a component that instructs your DAO as to how it should behave – kind of like a way of programming your Tivo/Set top box/VCR (for those who still have one ;)).
MockControl control = MockControl.createControl(WorkItemDao.class); WorkItemDao mockDao = (WorkItemDao) control.getMock(); WorkItemServiceImpl service = new WorkItemServiceImpl(); service.setWorkItemDao(mockDao);
The MockControl class is used to get an instance appropriate to the interface we are mocking up. From this, calling getMock() will return to us an implementation of our DAO interface which we then set on the instance of the class we are testing. This would normally be done in the setUp() method of your jUnit test class, so that each of your tests is guaranteed to get a mock instance in a fresh state, which you can then play with.
In our test method, we can then get on with doing some work. First, we tell our DAO exactly how we would like it to behave:
// set the methods that you expect to be called mockDao.getWorkItem(1); // set the return value WorkItem returnedWorkItem = new WorkItem(); returnedWorkItem.setWorkItemNo(1); control.setReturnValue(returnedWorkItem); // reset the control object to play back our script control.replay();
The last line tells the mock control object that the mock DAO is now in a state where the test can be run on it.
WorkItem workItem = service.generateWorkItem(1); assertNotNull(workItem); assertEquals(1, workItem.getWorkItemNo()); // verify that the methods we expected to be called on the mock object // were actually called control.verify();
The last line tells the control object to check itself to ensure that all the methods that we told it would be called were in fact called. It will throw an Exception if they weren’t causing our test to fail.
The behaviour described above can be used to test the behaviours of your service class under any circumstances. We can mock up the throwing of an Exception, unexpected behaviours, whatever we want. Here’s the full test class:
package jkorab.example.mock; import jkorab.example.mock.WorkItem; import jkorab.example.mock.WorkItemDao; import jkorab.example.mock.WorkItemException; import jkorab.example.mock.WorkItemServiceImpl; import org.easymock.MockControl; import junit.framework.TestCase; public class WorkItemServiceImplTest extends TestCase { private MockControl control; private WorkItemDao mockDao; private WorkItemServiceImpl service; public void setUp() { control = MockControl.createControl(WorkItemDao.class); mockDao = (WorkItemDao) control.getMock(); service = new WorkItemServiceImpl(); service.setWorkItemDao(mockDao); } /** * Checks that a WorkItem will be returned if the class receives a workItem * number greater than 0. * * @throws WorkItemException */ public void testGenerateWorkItem() throws WorkItemException { // set the methods that you expect to be called mockDao.getWorkItem(1); // set the return value WorkItem returnedWorkItem = new WorkItem(); returnedWorkItem.setWorkItemNo(1); control.setReturnValue(returnedWorkItem); // reset the control object to play back our script control.replay(); WorkItem workItem = service.generateWorkItem(1); assertNotNull(workItem); assertEquals(1, workItem.getWorkItemNo()); // verify that the methods we expected to be called on the mock object // were actually called control.verify(); } /** * Checks that a null will be returned if the class receives a workItem * number equal to 0 rather than throwing an exception. * @throws WorkItemException */ public void testGenerateWorkItemNullValue() throws WorkItemException { // set the methods that you expect to be called mockDao.getWorkItem(0); // set the control to throw an exception control.setThrowable(new WorkItemException()); control.replay(); WorkItem workItem = service.generateWorkItem(0); assertNull(workItem); } }
This is a great way to test, not only because of its simplicity, but also it being future proof. Let’s examine another way of writing the same tests without using mock objects:
WorkItemDao mockDao = new MockDao() { public WorkItem getWorkItem(int workItemNo) throws WorkItemException; WorkItem returnedWorkItem = new WorkItem(); returnedWorkItem.setWorkItemNo(1); } }; WorkItemServiceImpl service = new WorkItemServiceImpl(); service.setWorkItemDao(mockDao); WorkItem workItem = service.generateWorkItem(1); assertNotNull(workItem); assertEquals(1, workItem.getWorkItemNo());
At first glance, coding up an anonymous class looks like less work, but consider the following:
- if your class is more complex than this (and to be honest, most are) then you will end up with potentially dozens of anonymous implementations.
- if the DAO has more than one method, you will end up with a lot of code that does nothing.
- if the interface on your DAO changes then you will end up with a lot of tests that won’t compile, because your classes no longer match the interface.
This just isn’t the case with mock objects. Mock objects are created at runtime, and you only have to define the behaviours that you are interested in. The technique can also be used to test existing code – refactor your dependencies to an interface, use DI or a constructor if this isn’t an option, and voila, a testable class. 100% code coverage, and future-proof. No more excuses.
If you are interested in more info on mock objects check out the MockObjects blog.