Matthew Boston

Null Object in Groovy

When writing tight unit tests, you should use the Null Object Pattern in order to isolate the method under test. Here is a helper class I would use when writing unit tests in Groovy.

If you aren’t familiar with the Null Object Pattern, I suggest taking a look now. It’s not a pattern used only in the Groovy programming language. In fact, I got the idea for this blog post while writing RSpec tests at night while simultaneously working on a Grails application for a client. RSPec Mocks is where you’ll find my inspiration.

First, let me show you what the AsNullObject class looks like.

class AsNullObject {
  def propertyMissing(String name) {
    return this
  }

  def methodMissing(String name, args) {
    return this
  }
}

When writing unit tests, you need not care what any collaborator objects do or (hopefully) their side effects. So, with a little meta-programming magic, no more MissingMethodException or MissingPropertyException. Even better, no more 15 lines of test setup. Happy dance.

Happy dance

Here’s an example.

groovy> myNullObject = new AsNullObject()
Result: AsNullObject@5a06eeee

groovy> myNullObject.something()
Result: AsNullObject@5a06eeee

groovy> myNullObject.something().andAnother()
Result: AsNullObject@5a06eeee

groovy> myNullObject.attribute
Result: AsNullObject@5a06eeee

groovy> myNullObject.attribute.anotherAttribute
Result: AsNullObject@5a06eeee

Whew. Not so bad, eh?

In the context of a unit test, I would use it like so.

void testFireWeapon() {
  ammo = new AsNullObject()
  weapon = new BFG(ammo)
  assert weapon.fire() == "BOOM!"
}

For our test, we probably don’t want to actually fire any real ammo. But, we want our system to behave naturally and not throw errors.

I hope this helps.

Cheers.