问题
My env configs: Java 1.7u51, Grails 2.3.7
I'm trying to assert response.text in Controller Test but it always brings "".
What's happening?
This is my UserController
class UserController {
def index() {
flash.errors = "$params.secret"
render view: "index", model: [model: params.toModel,
text: params.username]
}
}
This is /user/index.gsp file
${text}
This is my Specification
@TestFor(UserController)
class UserControllerSpec extends Specification {
def setup() {
}
def cleanup() {
}
void "test something"() {
given:
params.username = "USERNAME"
params.password = "SECRET"
params.toModel = "Model"
when:
controller.index()
then:
flash.errors
view == "/user/index"
params.username == response.text
model.model == params.toModel
}
}
And test report is:
Failure: |
test something(teste.UserControllerSpec)
|
Condition not satisfied:
params.username == response.text
| | | | |
| USERNAME | | ""
| | org.codehaus.groovy.grails.plugins.testing.GrailsMockHttpServletResponse@46f29a61
| false
| 8 differences (0% similarity)
| (USERNAME)
| (-------)
[username:USERNAME, password:SECRET, toModel:Model]
回答1:
It is only the case of a template rendering where the content of the template is directly rendered to response as String. Hence response.text can only be used when a template is rendered unlike in this case where a view is being rendered.
In order to test rendering a view, GroovyPageUnitTestMixin has to be used as below:
import grails.test.mixin.TestMixin
import spock.lang.Specification
import grails.test.mixin.web.GroovyPageUnitTestMixin
@TestMixin(GroovyPageUnitTestMixin)
class UserControllerSpec extends Specification {
def controller
def setup(){
controller = testFor(UserController)
}
void "test something"() {
given:
params.username = "USERNAME"
params.password = "SECRET"
params.toModel = "Model"
when:
controller.index()
then:
flash.errors
view == "/user/index"
model.model == params.toModel
//method provided by mixin which mimics render method in
//controller. Make sure model is also passed in the map arg
//since view uses model.text
render(view: "/user/index", model: model) == 'USERNAME'
}
}
Note:
@TestForis replaced with the Mixin in the test. Therefore, controller has to be mocked as seen insetup()usingtestFor()method.render()can also be used to test template rendering with the keytemplatesimilar to the usage of keyviewin the map argument.
来源:https://stackoverflow.com/questions/23122666/grails-controller-unit-test-doesnt-render-page-to-response-text