(Quick Reference)

15.1.8 Unit Test Metaprogramming

Version: 3.2.4

15.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 myapp

import grails.test.mixin.*
import spock.lang.Specification

@TestFor(SomeController)
class SomeControllerSpec extends Specification {


    def setupSpec() {
        SomeClass.metaClass.someMethod = { ->
            // do something here
        }
    }

    // ...
}
package myapp

import grails.test.mixin.*
import org.junit.*

@TestFor(SomeController)
class SomeControllerTests {

    @BeforeClass
    static void metaProgramController() {
        SomeClass.metaClass.someMethod = { ->
            // do something here
        }
    }

    // ...

}