简体   繁体   中英

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? 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. In this case, it is the BookController . It's created by Grails for you to use in your unit tests.

controller.searchService is the BookController's reference to the SearchService bean, which you mock in the given block.

controller.search() is calling the BookController's search action.

controller.response.text is the text output that the action writes to the response.

The Testing docs are for the newest, Trait-based, version of the testing framework but the concepts are still the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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