See the light - agile, industrial strength, rapid web application development made easy

(Quick Reference) # 12.1.8 Unit Test Metaprogramming - Reference Documentation Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith, Lari Hotari Version: 2.3.8 ## 12.1.8 Unit Test Metaprogramming If runtime metaprogramming needs to be done in a unit test it needs to be done early in the process before the unit testing environment is fully initialized. This should be done when the unit test class is being initialized. For a Spock based test this should be done in the `setupSpec()` method. For a JUnit test this should be done in a method marked with `@BeforeClass`.

    package myappimport grails.test.mixin.*
    import spock.lang.Specification@TestFor(SomeController)
    class SomeControllerSpec extends Specification {
        def setupSpec() {
            SomeClass.metaClass.someMethod = { ->
                // do something here
            }
        }    // …
    }

    package myappimport grails.test.mixin.*
    import org.junit.*@TestFor(SomeController)
    class SomeControllerTests {    @BeforeClass
        static void metaProgramController() {
            SomeClass.metaClass.someMethod = { ->
                // do something here
            }
        }    // ...}
| Quick Reference (hide)