« I think there's a modern art exhibition in here somewhere... | Main | A Hammer your only tool? What if it suddenly tripled in price? »

September 17, 2005

Why I Love Testing Command Objects

Classes following the GoF Command pattern are readily suited to easy unit testing:

Now there are probably plenty of other patterns lending themselves to easily testable solutions, but I've been concentrating on Command implementations recently, so they've got my focus.

The general pattern I use for my (JUnit) unit test methods is test<MethodUnderTest><Intention>. For example:

  • testValidatePasswordFailsWithPreviouslyUsedPassword
  • testPopulateAccountMatchesNameAndAccountNumber

As you can imagine, some of these method names get rather long and I'm constantly fighting a battle between clarity and brevity. But when it comes to testing Command implementations, the MethodUnderTest part of my method name just disappears, given that execute is usually the only accessible method worth testing.

Love it!

Posted by Andy Marks at September 17, 2005 03:50 PM

Comments

Uh? How many commands do you need to write?

Most times, I can get away with a handful of command objects. Usually, I have a Command with a repository, a Class object (for the type of object to load), an ID (to identify the object) and one of the following:

* A map to be populated with data from the object
* A map to populate the object and then save it.
* A method name and an array of arguments to invoke.

And that's really about it.

One of the risks of the Command Pattern is you end up with an anemic Domain model, with all the logic pushed out to the commands. By relying on generic commands and reflection, you keep the logic in the domain model, and you don't end up writing that many commands.

Posted by: Robert Watkins at September 15, 2005 02:10 PM

Amen to that brother !

We're working on a relatively simple web application, where I've implemented a FrontController (we don't need no stinking frameworks) and using the Command pattern based on the inputs from the web pages.

The team was a little confused at first, but they're all really starting to get the whole hang of dependency injection and unit testing.

It is working out very, very well.

Posted by: Jon Eaves at September 15, 2005 03:09 PM

Haven't you just described WebWork?

Posted by: Peter Moran at September 23, 2005 10:06 AM

Post a comment

Thanks for signing in, . Now you can comment. (sign out)

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)


Remember me?