Thursday, 15 May 2008

Fear & Loathing in the MetaClassRegistry

On your testing travels you may, on occasion, mock methods out on certain classes using the old metaClass trick:
MyLovelyClass.metaClass.'static'.myLovelyMethod = { //crazy stuff here }

Now the fun with this approach is that when/how/where/how long/huh? feeling you get when you realize that other tests in the the suite start failing - dreaded test bleed (insert dramatic soundclip here).

Thanks to the Groovy method reference operation (&) and the MetaClassRegistry all can be made well, without having to resort to sticking all the initial method references in a map (or similar) and trying to stuff it all back on the original class in your tearDown():
void tearDown() {
def remove = GroovySystem.metaClassRegistry.&removeMetaClass
remove MyLovelyClass
}

Hmmm. I feel a bit lightheaded. Maybe you should drive.

2 comments:

Rob said...

...and then you notice that sinking feeling you get when you realise all the Grails dynamic methods and properties have been stripped off your class as well

Gus Power said...

Ah, mah little pirate frend, good point. A post on testing grails archetypes is due.