Grails自定义taglib在集成测试期间无法使用自定义工件

时间:2012-11-29 16:03:58

标签: testing grails grails-plugin taglib grails-2.0

我编写了一个包含自定义TagLib的插件,该插件本身使用自定义的artefact实例。当插件包含在应用程序中时,taglib完全按预期工作。但是,我无法为它编写集成测试。

假设自定义artefact类型为“Foo”且artefact handler类为FooArtefactHandler

(简化)FooTagLib类看起来像这样:

class FooTagLib {

    static namespace = "bar"

    def eachFoo = { attrs, body ->
        grailsApplication.fooClasses.each { foo ->
            out << body()
        }
    }
}

关联的FooTagLibTests类如下所示:

import grails.test.mixin.*

@TestFor(FooTagLib)
class FooTagLibTests {

    void testEachFoo() {
        grailsApplication.registerArtefactHandler(new FooArtefactHandler())
        // Classes AFoo and BFoo are in the test/integration folder
        grailsApplication.addArtefact(FooArtefactHandler.TYPE, AFoo)
        grailsApplication.addArtefact(FooArtefactHandler.TYPE, BFoo)
        // just to check if artefacts are correctly loaded
        assert grailsApplication.fooClasses.length == 2

        assert applyTemplate("<bar:eachFoo>baz</bar:eachFoo>") == "bazbaz"
    }
}

当我运行此测试时,结果如下:

| Failure:  testeachFoo(com.my.package.FooTagLibTests)
|  org.codehaus.groovy.grails.web.taglib.exceptions.GrailsTagException: Error executing tag <bar:eachFoo>: No such property: fooClasses for class: org.codehaus.groovy.grails.commons.DefaultGrailsApplication

taglib中的grailsApplication似乎与测试中的实例不同。谁可以给我解释一下这个?我在这里做错了吗?

1 个答案:

答案 0 :(得分:1)

如果这是集成测试,则不应使用@TestFor,而应扩展GroovyPagesTestCase并声明grailsApplication:

class FooTagLibTests extends GroovyPagesTestCase {

    def grailsApplication

    void testEachFoo() {
        grailsApplication.registerArtefactHandler(new FooArtefactHandler())
        // Classes AFoo and BFoo are in the test/integration folder
        grailsApplication.addArtefact(FooArtefactHandler.TYPE, AFoo)
        grailsApplication.addArtefact(FooArtefactHandler.TYPE, BFoo)
        // just to check if artefacts are correctly loaded
        assert grailsApplication.fooClasses.length == 2

        assert applyTemplate("<bar:eachFoo>baz</bar:eachFoo>") == "bazbaz"
    }
}

那是因为TestFor注释会模拟grailsApplication的实例(在单元测试中使用)。