【问题标题】:How to make multiple requests with different data in Grails Integration tests如何在 Grails 集成测试中使用不同的数据发出多个请求
【发布时间】:2013-09-16 18:10:50
【问题描述】:

我正在使用 Spock 插件编写 Grails 2.2.1 集成测试,其中我试图将两组数据发布到同一个控制器端点:

when: "The user adds this product to the inventory"
def postData = [productId: 123]
controller.request.JSON = postData
controller.addToInventory()

and: "Then they add another"
def secondPostData = [productId: 456]
controller.request.JSON = secondPostData
controller.addToInventory()

then: "The size of the inventory should be 2"
new JSONObject( controller.response.contentAsString ).inventorySize == 2

我看到的问题是两个请求都将相同的 JSON 提交给 addToInventory()。

This StackOverflow question 建议调用 controller.request.reset(),但这不起作用(没有方法签名:org.codehaus.groovy.grails.plugins.testing.GrailsMockHttpServletRequest.reset())。

我正在尝试的可能吗?

【问题讨论】:

  • 需要注意的重要一点是使用 controller.request.JSON 将数据传递给 post 方法!真的很难找到。

标签: testing grails integration spock


【解决方案1】:

虽然 Anuj 我们纠正了应该使用 where 子句来保持测试干净,但有时测试需要运行多个请求。就我而言,我想测试当它收到 2 个重复 POSTS 时,第 2 个被正确拒绝。

我发现重置响应可以满足我的需要:

controller.response.reset()

清除响应。

【讨论】:

    【解决方案2】:

    实际上还有另一种方式。插入:

    GrailsWebUtil.bindMockWebRequest()
    

    在您的第二次测试开始时。这将有效地创建一个新的 ServletContext、一个新的 MockHttpServletRequest、一个新的 MockHttpServletResponse,然后将所有三个绑定到当前线程中。

    【讨论】:

      【解决方案3】:

      "Where:" 可用于在 spock 测试框架中执行数据驱动测试。尝试使用以下示例:

      when: "The user adds this product to the inventory"
      
      controller.params.JSON = [productId:productId]
      controller.addToInventory()
      
      then: "The size of the inventory should be 2"
      new JSONObject( controller.response.contentAsString ).inventorySize == 2
      
      where:
      
      ID|productId
      1|123
      2|456
      

      希望对你有帮助!!!

      【讨论】:

      • 感谢 Anuj,我已将测试重构为类似于您上面的示例。我如何为请求分配参数也有问题,所以controller.request.JSON = [productId:productId] 行现在是controller.params.JSON = [productId:productId]
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-10
      • 2019-10-13
      • 1970-01-01
      • 1970-01-01
      • 2019-12-11
      • 2015-04-10
      • 2019-03-09
      相关资源
      最近更新 更多