断言控制器返回的视图文件中存在文本。

时间:2016-07-20 05:16:11

标签: grails integration-testing

我有一个简单的测试控制器。

package taglibexample

class HelloWorldController {

    def index() {       

        render(view: "index",  model: [id:2])
    }
}

上述控制器呈现的视图如下:

<!doctype html>
<html>
<head>

<title> Hello World </title>
</head>

<body>

<h1> Hello World! ${ id } </h1>

</body>

</html>

现在,我想测试这个控制器方法并断言是否存在文本&#34; Hello World! 2&#34 ;.我到目前为止的代码并没有起作用如下:

package taglibexample

import static org.junit.Assert.*
import org.junit.*

class HelloTests {

    def controller


    @Before
    void setUp() {

        controller = new HelloWorldController()
    }


    @Test
    void testSomething() {

        def model = controller.index()

        assertTrue controller.response.getContentAsString().contains("Hello World! 2") 


    }

}

我该怎么做到这一点?我感谢任何帮助!谢谢!

1 个答案:

答案 0 :(得分:-1)

Grails文档似乎以非常明确的方式声明了这一点,为您的grails版本选择合适的文档

例如,在grails 2.5.5中查看此示例:

import grails.test.mixin.TestFor
import spock.lang.Specification

@TestFor(SimpleController)
class SimpleControllerSpec extends Specification {

    void "test hello"() {
        when:
        controller.hello()

        then:
        response.text == 'hello'
    }
}

它测试框架生成的实际响应。在这种情况下,它是非常简单的单词,但它可以呈现视图而不是视图的名称