如何在Grails集成测试中使用不同数据进行多个请求

9

我正在使用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() 方法中进行处理。

这个 StackOverflow 的问题 建议调用 controller.request.reset() 方法,但这并没有奏效(No signature of method: org.codehaus.groovy.grails.plugins.testing.GrailsMockHttpServletRequest.reset())。

我所尝试的这种方式是否可行?


一个重要的事情需要注意,就是使用controller.request.JSON来传递数据给post方法!这真的很难找到。 - Neoecos
3个回答

6
"

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

希望这有所帮助!!!

2
谢谢Anuj,我已经重构了测试代码,使其看起来像你上面的示例。我之前分配请求参数的方式也有问题,所以现在controller.request.JSON = [productId:productId]这一行变成了controller.params.JSON = [productId:productId] - Bryan O'Sullivan

3
实际上还有另一种方式。插入:
GrailsWebUtil.bindMockWebRequest()

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

0

虽然Anuj正确地指出where子句应该用于保持测试的清晰,但有时测试需要运行多个请求。在我的情况下,我想测试当它接收到2个重复的POSTS时,第二个被正确拒绝。

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

controller.response.reset()

清除响应。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接