unit-testing - 使用 Controller 的 Grails Spock 单元测试断言 View

标签 unit-testing grails spock

  • 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.viewviewresponse.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/

相关文章:

web-services - 如何使用 Rhino Mocks 模拟 WCF Web 服务

mysql - 通过连接提高 Grails CreateCriteria 查询速度

json - 在Spock中将模拟转换为JSON

spring-boot - 有没有办法在使用 Spock 框架时使用 @MockBean 注释

testing - 如何在 spock 测试中使用 `then` block

javascript - npm test 出错,但 mocha test node.js 出错

接口(interface)上的 phpUnit 代码覆盖率显示没有成功

javascript - 单元测试 nodejs 事件

grails - 左联接grails标准

grails - 在 Grails/Groovy 中加载插件管理器时出错