Mock mock objects for RPC testing

The project I’m currently working on is based around a set of classes representing documents. These get some of their methods exposed in a simple REST web service interface, which is how the AJAX-y web front-end drives them.

Back when it started, I had two document test scripts: one which called them directly, and the other via RPC. The scripts had a tendency to get out of sync, as features would be added to the documents, incorporated into the direct test script, and left out of the RPC script.

Eventually the document script was so fat that I chopped it up into ten more behavioural scripts, which made things much easier to manage. Only now my RPC script was beyond all hope, which was a bit of a problem: if the objects didn’t work under RPC, the app would be useless.

I’ve never user mock objects for testing, but the technique I came up with to bring the RPC test up to speed reminded me a little of what I know about them. So I named them mock-documents, which is probably a misnomer.

The mock-document is initialised with the same parameters as a real document: all it contains, apart from the creator, is an AUTOLOAD method. When any method is called on it, AUTOLOAD converts it and its parameters into a URL and tries to invoke it via RPC, returning the results in the same format as the real document would. There’s a bit of fooling around needed at this stage – most of the methods return hashrefs, but a well-defined subset return straight XML.

The test scripts now run twice: once on the real documents, and once on the mock-document versions. All the RPC stuff is transparent to the tests, and any changes from now on will apply to both the direct and RPC documents.

All this was made much easire by the fact that all the document test scripts get their document objects from a single test document factory class – so it’s the only thing that needs to even know about the mock-documents. But that’s a topic for another post.

The reason mock-documents is a misnomer is that there really is a real document in there, behind the RPC layer.

Another advantage of this technique: anything that looks under the hood of the objects under test will break as soon as it’s run on the RPC version, so it’s a way to tell if your tests are really as black-box as you thought they were. Mine aren’t.

Leave a Reply