Mocking and stubbing in Groovy with ‘with’
I often use metaClass in Groovy to create mocks or stubs in my unit tests. Recently I’ve discovered that the with method makes this a bit simpler.
This:
Foo.metaClass.with {
doSomething = {
return true
}
anotherThing = {foo ->
assertEquals 42, foo
}
}
is slightly shorter than this:
Foo.metaClass.doSomething = {
return true
}
Foo.metaClass.anotherThing = {foo ->
assertEquals 42, foo
}
and less code means less bugs.
[Update: For more explanation of why the with method is so great, read this post.]
[Update: And for another way to write your mocks and stubs, see my previous post on mocking with Groovy.]
Recent Comments