Testing with mock objects

I put together a workshop for the team at work on unit testing and design with mock objects. I opted to show a small sample using both EasyMock and JMock. I'd used JMock before but EasyMock had some nice surprises in store for me. The two things that stood out immediately for me with EasyMock were:

1. No need to subclass my test case. This has always bothered me about JMock because when you have two libraries that both require subclassing a JUnit TestCase such as XMLUnit and JMock, you're up a creek.
2. In the record phase you call the method on the mocked object so you get to use IDE code completion (if the interface already exists), IDE method signature and stub creation, and refactoring abilities. Whereas with JMock you pass the method to call as a string which has two disadvantages in my opinion. First, when practicing TDD I like to call method names that don't exist on my interfaces yet and then have the IDE create the method signature in the interface and method stubs in the implementation classes. Second, after a refactoring you'll either need an IDE that knows when you rename a method to also replace that method name in strings, or you'll have to do a project or workspace wide search and replace.

The author of JMock has written a JMock and EasyMock comparison that's worth reading. I also know of these open-source projects that use mock objects: Tapestry and Hivemind use EasyMock, AppFuse uses JMock, and ONess uses JMock. If you know of other open-source projects that use one library or the other please post a comment!

Lastly I'll leave a reference to Martin Fowlers article touching on JMock, EasyMock, and the differences between mock objects and stubs.

This entry was posted in Java. Bookmark the permalink.