简体   繁体   English

Grails单元测试控制器字段

[英]Grails unit test controller field

Can someone tell me what the controller object in controller .searchService, controller .search() and controller .response.text.contains refers to? 谁能告诉我什么控制器 .searchService, 控制器 .search()和控制器 .response.text.contains 控制器对象是指? How is this controller object created and what is its purpose? 该控制器对象是如何创建的,其目的是什么?

import grails.test.mixin.TestFor
import spock.lang.Specification
@TestFor(BookController)
@Mock(Book)
class BookControllerSpec extends Specification {

    void "test search"() {
        given:
        def searchMock = mockFor(SearchService)
        searchMock.demand.searchWeb { String q -> ['first result', 'second result'] }
        searchMock.demand.static.logResults { List results ->  }
        controller.searchService = searchMock.createMock()

        when:
        controller.search()

        then:
        controller.response.text.contains "Found 2 results"
    }
}

controller is an instance of your Controller under test, specified in the @TestFor annotation. controller是在@TestFor批注中指定的@TestFor Controller的实例。 In this case, it is the BookController . 在这种情况下,它是BookController It's created by Grails for you to use in your unit tests. 它由Grails创建,供您在单元测试中使用。

controller.searchService is the BookController's reference to the SearchService bean, which you mock in the given block. controller.searchService是BookController对SearchService bean的引用,您可以在给定的块中进行模拟。

controller.search() is calling the BookController's search action. controller.search()正在调用BookController的search动作。

controller.response.text is the text output that the action writes to the response. controller.response.text是操作写入响应的文本输出。

The Testing docs are for the newest, Trait-based, version of the testing framework but the concepts are still the same. 测试文档适用于基于测试框架的最新版本,但是概念仍然相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM