【问题标题】:testing grails iterative taglibs that use variables in body测试在正文中使用变量的 grails 迭代标记库
【发布时间】:2011-04-08 20:54:51
【问题描述】:

我有一个相当简单的 taglib 像这样(查询被简化为示例):

def toptopics = { attrs, body ->
    def topics = Topic.executeQuery("from Topic")

    topics.each { topic -> 
        out << body(topic:topic)
    }
}

然后我在gsp中使用如下:

    <g:toptopics>
        <li><a href="#">${topic.name}</a></li> 
    </g:toptopics>

然后我正在尝试为它编写一个测试(代码如下):

void setUp() {
    taglib = new MySampleTagLib()
}

void test_each_in_collection() {
    assertEquals("tag 1;tag 2", taglib.toptopics() { "${topic.name};" })
}

但它总是失败。测试输出抱怨“没有这样的属性:类的主题:MySampleTagLibTests

由于某种原因,它试图在将字符串传递给 taglib 之前评估 ${topic.name}。我试过逃避美元唱,但没有成功。这方面有什么建议吗?

【问题讨论】:

    标签: testing grails groovy taglib


    【解决方案1】:

    要测试标签库,您应该扩展TagLibUnitTestCase。当您使用此类时,您不会直接实例化您的标记类(如上面的代码中所示),而是通过tagLib 属性为您提供一个实例。例如,假设我要测试FooTagLibrepeat 标签。此标记采用单个属性,并期望标记具有使用变量的主体。

    class FooTagLibTests extends TagLibUnitTestCase {
    
      FooTagLibTests() {
        // This line isn't necessary in this case because the test class is in the same package 
        // as the tag class and named ${TagLib}Tests
        super(FooTagLib)
      }
    
      void testRepeat() {
    
        def someText = 'blah'
    
        // tagLib references an instance of FooTagLib. Invoke the bar tag passing it attribute
        // values and a body
        tagLib.repeat(times: '2') {
          "body $someText "
        }
    
        // compare the expected and actual output
        assertEquals 'body someText body someText ', tagLib.out.toString()
      }
    }
    

    【讨论】:

    • 这应该适用于 grails 1.3.5 吗?另外,如果 $someText 在 taglib 中定义,为什么需要在测试中声明它?在我的情况下,即使使用 TagLibUnitTestCase 它仍然会失败并显示相同的消息。
    • 如果您显示代码和错误消息,也许我可以帮助您
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-18
    • 2019-11-21
    • 1970-01-01
    • 2019-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多