- Grails 2.2.4
- 斯波克 0.7
我正在尝试测试是否从 grails Controller 呈现了正确的 View 。我的创建方法如下所示:
def create() {
def documentCategories = DocumentCategory.list()
def documentTypes = DocumentType.list()
def documentComponents = DocumentComponent.list()
[documentCategories: documentCategories,
documentTypes: documentTypes,
documentComponents:documentComponents]
}
还有我的测试:
def "test create action"() {
given:
def model = controller.create()
expect:
response.status == 200
model.documentCategories.size() == 0
model.view == '/document/create'
}
我尝试过各种版本的 model.view
包括:
view == '/document/create'
response.forwardedUrl == '/document/create'
所有这些都失败了,因为 model.view
、view
和 response.forwardedUrl
都是空的。有什么建议吗?
最佳答案
由于您没有在 Controller 方法中显式定义 View ,因此将采用 Grails 约定。根据文档,将选择与 Controller 名称和方法匹配的 View --> view: "controllerName/methodName"
关于您的问题,您不应该测试 Grails 框架是否正常工作。您应该测试您的 Controller 的行为是否如您所愿。
在这种情况下,您想要测试您的 Controller 是否未指定 View ,因为这是 Controller 的预期行为。
对此的测试将是:
then:
controller.modelAndView == null
response.redirectedUrl == null
如果您在 Controller 中调用“render(view: xxx)”,就会创建 modelAndView。
在 Controller 中调用 redirect() 或 chain() 会导致 response.redirectedUrl 被填充到单元测试中
关于unit-testing - 使用 Controller 的 Grails Spock 单元测试断言 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18447297/