Skip to content

Instantly share code, notes, and snippets.

@deigote
Created June 10, 2014 14:17
Show Gist options
  • Save deigote/2234981b9ec74b16b7f5 to your computer and use it in GitHub Desktop.
Save deigote/2234981b9ec74b16b7f5 to your computer and use it in GitHub Desktop.
Groovy - ExpandoWithDelegate
class ExpandoWithDelegate {
private delegate
private Map<String, Closure> mockedMethods
ExpandoWithDelegate(delegate) {
this.delegate = delegate
this.mockedMethods = [:]
}
def methodMissing(String name, args) {
mockedMethods.containsKey(name) ?
mockedMethods[name](*args) :
delegate."$name"(*args)
}
def propertyMissing(String name, value) {
if (value instanceof Closure) {
value.delegate = delegate
mockedMethods[name] = value
}
else throw new MissingPropertyException(name, delegate.getClass())
}
}
def var = new ExpandoWithDelegate('me molo')
assert var.size() == 7
var.size = { -> 42 }
assert var.size() == 42
assert var.concat(' mucho') == 'me molo mucho'
var.concat = { anotherString -> delegate.concat(anotherString).concat('!!!') }
assert var.concat(' mucho') == 'me molo mucho!!!'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment