Testing 如何在Grails集成测试中使用不同的数据发出多个请求

Testing 如何在Grails集成测试中使用不同的数据发出多个请求,testing,grails,integration,spock,Testing,Grails,Integration,Spock,我正在使用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 =

我正在使用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
我看到的问题是,两个请求的addToInventory()都提交了相同的JSON

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

我尝试的是可能的吗?

“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

希望有帮助

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

GrailsWebUtil.bindMockWebRequest()

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

尽管Anuj us纠正了应该使用
子句保持测试干净的错误,但有时测试需要运行多个请求。在我的例子中,我想测试一下,当它收到两个重复的帖子时,第二个被正确地拒绝了

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

controller.response.reset()

为了清除响应。

谢谢Anuj,我已经重构了测试,使其看起来像上面的示例。我如何为请求分配参数也有问题,因此行
controller.request.JSON=[productId:productId]
现在是
controller.params.JSON=[productId:productId]
。需要注意的一点是使用controller.request.JSON将数据传递给post方法!真的很难找到。