I'm having trouble with replacing and then restoring a method using
metaClass, to override behaviour for a test. Any help much appreciated.
In one of my tests, I inject:
Foo.metaClass.myBusinessLogic = { /* record stuff here */ }
That works well for intercepting the (expensive) call and recording it.
But everything in the test suite then subsequently fails because the
method is now a no-op! I've been trying to restore the original method
in the tearDown.
---
My attempts have involved code like that below. But for each of my
attempts, it keeps writing out "replacement".
class ReplacingAndRestoringMetaMethod {
public static void main(String[] args) {
def origMethod = Foo.metaClass.myBusinessLogic
//def origMethod2 =
Foo.metaClass.getMetaMethod("myBusinessLogic", new Object[0])
Foo.metaClass.myBusinessLogic = { println "replacement" }
Foo.metaClass.myBusinessLogic = origMethod
new Foo().myBusinessLogic()
}
}
public class Foo {
public void myBusinessLogic() { println "orig" }
}
Thanks, Aled
p.s. I'd prefer to use
http://docs.codehaus.org/display/GROOVY/Groovy+Mocks, but the code
hasn't been written to support such injection...
---------------------------------------------------------------------
To unsubscribe from this list, please visit:
http://xircles.codehaus.org/manage_email
In order to restore the original method you might try putting this in
the tearDown:
GroovySystem.metaClassRegistry.removeMetaClass Foo
This may have the same effect:
Foo.metaClass = null
Cheers,
Dinko
Foo.metaClass.'static'.bar = { "Mocked" }
What's the best way restore bar to it's original state? Or is there a
better solution (I hope).
--
View this message in context: http://groovy.329449.n5.nabble.com/metaclass-how-to-replace-and-restore-a-method-tp5042834p5494930.html
Sent from the groovy - user mailing list archive at Nabble.com.
class Foo {
static def bar() {
'Original'
}
}
assert "Original" == Foo.bar()
Foo.metaClass.'static'.bar = {"Mocked" }
assert "Mocked" == Foo.bar()
Foo.metaClass = null
assert "Original" == Foo.bar()
Foo.metaClass.'static'.bar = {"Mocked" }
assert "Mocked" == Foo.bar()
Foo.metaClass = null
assert "Original" == Foo.bar()
--
View this message in context: http://groovy.329449.n5.nabble.com/metaclass-how-to-replace-and-restore-a-method-tp5042834p5494972.html
Yes, that has worked for me too but if you have two methods, how would you revert just one to it's original version.
Ed
--
View this message in context: http://groovy.329449.n5.nabble.com/metaclass-how-to-replace-and-restore-a-method-tp5042834p5509270.html