Null Object in Groovy
tl;dr
A small Groovy class, AsNullObject, uses methodMissing and propertyMissing to return itself for any call. Pass it to the code under test in place of collaborators you do not care about, and skip the long mock setup.
Key takeaway: Use a null object for irrelevant collaborators so a unit test isolates the one method it checks.
When writing tight unit tests, you should use the Null Object Pattern 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.

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.