JMock is your friend…
JMock does actually look quite similar to what I’ve done, but it is focussed more on the normal use of Mockobjects – ie. checking they were called with the expected values.
I’m not really doing Mocks at this point – its more like convincing an application that its running inside a real servlet container. Which means that I have to be able to understand that when I get a call like request.getHeader(“user-agent”), I need to return “Fakezilla”, but when I get request.getHeader(“if-modified-since”), I have to return a valid date string, or null. I’m not trying to assert how the mocks are called, just fake up a convincing looking environment. What I’ve ended up with is essentially a form of dynamic dispatch, as each mock has a collection of MethodReceivers in a Map keyed by method name, and each MethodReceiver has a Map of MethodReturn objects, keyed by an ArrayList of the arguments. Its then a case of calling getReturnValue on the MethodReturn object (confused yet?). I can therefore return different responses based on the actual values (not just type) of the arguments.
I can also simply make the Mock return a hard-coded response directly where I can get away with it (methods with no arguments for example).
There’s some syntactic ugliness in the setup code due to Java’s lack of enclosures – the closest approximation I’ve found is to implement an interface ‘in-place’ with an anonymous block. The alternative is hundreds of really tiny and very similar looking concrete classes.
The whole thing isn’t exactly generic or lightweight, as you have to know quite a lot about what your application is going to need in the way of parameters, and which methods its going to call on the request/response objects, but it has been quite illuminating finding out just how the application in question interacts with its environment.
And its nice to work on something a little off the wall every now and then 🙂