1

我编写了一个包含自定义 TagLib 的插件,该插件本身使用自定义人工制品实例。当插件包含在应用程序中时,标签库的工作方式与预期完全一样。但是,我无法为它编写集成测试。

假设自定义人工制品类型是“Foo”,人工制品处理程序类是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似乎与测试中的实例不同。谁可以给我解释一下这个?我在这里做错什么了吗?

4

1 回答 1

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 的实例(用于单元测试)。

于 2012-11-29T17:49:08.947 回答