Null object in Groovy
Key takeaway: Use a null object for irrelevant collaborators so a unit test isolates the one method it checks.
When a unit test doesn’t care about a collaborator, pass in a null object instead of writing 15 lines of mock setup. Here’s the helper class I use in Groovy. The idea comes from RSpec Mocks’ as_null_object, which I was using at night while working on a Grails app for a client during the day.
class AsNullObject {
def propertyMissing(String name) {
return this
}
def methodMissing(String name, args) {
return this
}
}
Any method call or property access returns the object itself. No more MissingMethodException or MissingPropertyException, and chained calls like myNullObject.something().andAnother() just keep working.
In a test, it looks like this:
void testFireWeapon() {
ammo = new AsNullObject()
weapon = new BFG(ammo)
assert weapon.fire() == "BOOM!"
}
We don’t want to fire real ammo in this test, but we still want the system to behave normally and not throw errors. The null object isolates the one method under test and gets everything else out of the way.
