2012-11-29 25 views
1

我已經編寫了一個包含自定義TagLib的插件,該自定義TagLib自身使用自定義的artefact實例。當插件包含在應用程序中時,taglib完全按照預期工作。但是,我無法爲其編寫集成測試。Grails自定義taglib在集成測試期間無法使用自定義製品

比方說,自定義的人工製品類型是「富」和製品處理類是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" 
    } 
} 

當我運行這個t EST,結果如下:

| 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 

在標籤庫的grailsApplication似乎不相同實例作爲一個在測試中。誰可以給我解釋一下這個?我在這裏做錯了什麼?

回答

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的實例(在單元測試中使用)。

+0

謝謝!它現在就像一種魅力! –

+0

我很高興幫助!考慮將此答案標記爲正確:) –

相關問題