Saturday, December 15, 2007

Less Tedious Tests with Easymock

If you have small, simple classes with clearly defined responsibilities you will inevitably have dependencies between them. You could use these collaborator classes directly with the 'new' operator, but if you do you will not be able to test your classes in isolation of each other and you will wind up with much duplication between your tests. It will also be difficult to test all of the scenarios that you might want to because of the behaviors of these collaborator classes. So instead you inject these collaborators into you class under test. This is better, but it does force you to create mock classes. These mock classes will often require behaviors in order to perform your test or gather information about the behavior of your class under test. One problem with this is that this behavior in your mock classes becomes difficult to maintain as the complexity of the behavior of your class under test increases. Another problem is that if you follow this strategy repeatedly you will develop a lot of test code that is redundant.

Easymock helps to avoid these problems. It will create mock objects for you and allow you to easily specify how your class under test is expected to use them. The following is a bit incomplete for the sake of explanation, so I encourage you to read the documentation.

Getting a new clock object:

IClock clock = Easymock.createMock(IClock.class);


Telling Easymock how the clock is expected to be used:

Easymock.expect(clock.getTime()).andReturn(new Date());


Then you give the clock object to your class under test to use and Easymock is able to notify JUnit of when and how your class under test used the collaborator in an unexpected way.

No comments: