I’ve been meaning to have a play with some of the “dynamic proxy” type mock frameworks out there for a while and yesterday I finally had a chance.
For most of consulting stuff I’m writing J2EE tests (EJB,MQ,JDBC,JNDI,Web stuff) and I’ve found Mockrunner to be the business. Huge fan. But MockRunner works on providing mock implementations of InitialContext, HttpServletRequest, and all those other essential classes in the JEE space.
What I was after was a way to mock out a particular interface in my own code (without writing an empty implementation of that interface by hand). There seems to be two main players in the “dynamic” style of the mocking space: EasyMock and JMock. They both seem to have a fair bit of traction, so I thought I’d take a look at both.
I had a look at JMock first, since it’s probably got the bigger buzz (and every codehaus project I’ve played with has been pretty smick). There were a couple of things that I had trouble with:
- Your test classes have to extends their
MockObjectTestCase
. This is a bit of a showstopper. I already have other JUnit base class extensions that I want to use (which I’ve hacked in some custom Spring stuff) and found this restriction pretty arbitrary. - Method names are stored in strings. It’s going to make refactoring a little trick… but not a showstopper by any means. I miss the command completion, so it’s a little annoying, but I can see what they’re doing at it makes sense from a design decision.
- Syntax sugar tastes a little sour at first. I’ve heard lots of good things about the “naturalness” of the JMock API and that your code reads like a spec. The whole idea looks pretty cool… and you end up with something pretty concise… but my head wasn’t there and the one example in the doco didn’t take me to a place where I could generalise in my own tests.
After getting a little frustrated with JMock, I thought I’d have a look as EasyMock. I first heard about EasyMock in an appendix to Pro Spring - geez that’s a good book - so I was keen to give it some airtime too. A few things:
Both APIs have the capacity to mock either interfaces or classes (though to mock classes you have to add a dynamic bytecode generator jar - to be expected). Both seem to have plenty of traction. Can’t really go wrong with either depending on your needs.
EasyMock is definitely the business for me. Looking forward to giving it a more solid workout over the next couple of weeks.