简体   繁体   中英

Grails unit test failing in Grails 2.x

We have a class that uses Groovy's invokeMethod interceptor to intercept all static method calls on a class. It's used to define rules pulled from the database. Recently, we upgraded to Grails 2.3.4 from 1.3.7 and the unit test testing this class is now failing if I invoke a method that has already been defined. It works fine if the method has not been defined. Here's a much simplified version of what we're doing.

class TestUtil {
static {

    TestUtil.metaClass.'static'.invokeMethod = { String m_name, args ->

        def method = TestUtil.metaClass.getMetaMethod(m_name, args)
        if(!method) {
            //define it
            TestUtil.metaClass.'static'."${m_name}" = { argz ->
                return argz[0]
            }
        }

        //call it
        "${m_name}"(args)
        }
    }
}

class TestUtilTest extends GrailsUnitTestCase {
void testMethodNotExist() {
    def result = TestUtil.testMethod("not exist")

    assertEquals result, "not exist"
}

void testExistingMethod() {
    def result = TestUtil.testMethod("exist")

    assertEquals result, "exist"
}
}

The error I get is: | groovy.lang.MissingMethodException: No signature of method: static TestUtil.testMethod() is applicable for argument types: (java.lang.String) values: [exist]

When used in the context of the application, the code works fine...it's just the unit test that's breaking and I can't quite figure out why.

Wow, from 1.3.7 to 2.3.4..... A giant leap for mankind. :)

You are getting the error because of extending GrailsUnitTestCase .

If you are not doing any kind of mocking in the test for the util class then you can modify the test class to extend GroovyTestCase instead of GrailsUnitTestCase . It should work.

GrailsUnitTestCase is not encouraged to use in newer version of Grails. With Grails 2.3.4 you get spock by default when you create tests from command line or create any artefact, and you should not see any problem either if you use spock test as below:

import spock.lang.Specification

class TestUtilSpec extends Specification {

    void "test both in one test case"(){
        expect:
            result == TestUtil.testMethod(arg)

        where:
            arg         || result
            "not exist" || "not exist"
            "exist"     || "exist"
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM