gpt4 book ai didi

json - Grails 2.2 对需要请求 JSON 内容的远程 Web 服务的功能测试

转载 作者:行者123 更新时间:2023-12-02 15:24:58 26 4
gpt4 key购买 nike

我正在使用 Grails 2.2 并且正在编写一个功能测试来验证从远程 Web 服务接收到的 JSON 响应。 Web 服务需要在请求中传递一些 JSON 内容。

当我使用“ postman ”之类的工具测试此 Web 服务时,我收到了正确的 JSON 响应。

Remote Web Service POST Request With JSON

为此,我在 Grails 2.2 中编写了一个功能测试用例。下面提供了我的示例代码片段。

import com.grailsrocks.functionaltest.*
import com.grailsrocks.functionaltest.client.APIClient

class RemoteWebServiceFunctionalTests extends TestCaseBase{

void testPost() {
post("http://remoteAddress:8080/services/getData", {
param1 = "value1"
param2 = "value2"
...
...
param3 = "value3"
})

assertStatus 200
}

@Override
Class getDefaultClientType() {
APIClient
}
}

下面提供运行测试用例的输出以供引用。
|Running 1 functional test... 1 of 1
--Output from testPost--
Switching to browser client [default]
Creating to new client [default] of type [class com.grailsrocks.functionaltest.client.APIClient]

== Making request POST http://remoteAddress:8080/services/getData parameters: ==
param1: value1
param2: value2
...
...
param3: value3

== Request headers: ============================================================
== Content =====================================================================

================================================================================
== Response was 200 (OK) headers: ==============================================
Server: Apache-Coyote/1.1
Content-Type: application/json
Content-Length: 148
Date: Fri, 27 Mar 2015 17:36:33 GMT
================================================================================
== Content =====================================================================
{"errors":[{"Error0001":"Invalid request. Please refer to API definition"}],"result":null,"warnings":null}
================================================================================

当我运行测试时,我确实得到了状态 200,但没有收到正确的 JSON 响应内容。我想我没有正确格式化请求。我需要知道在功能测试用例中将 JSON 内容提供给远程 Web 服务调用的正确方法。

最佳答案

我找到了在正文中提供 JSON 以发出 POST 请求的正确方法。

import com.grailsrocks.functionaltest.*
import com.grailsrocks.functionaltest.client.APIClient

class RemoteWebServiceFunctionalTests extends TestCaseBase{

void testPost() {

post("http://remoteAddress:8080/services/getData") {

headers['Content-Type'] = 'application/json'

body {
"""
{"param1":"value1","param2":"value2",...,"param3":"value3"}
"""
}
}

assertStatus 200

// assuming that the POST method is sending a response with the original request content,
// similar to the sample web service available at "http://httpbin.org/post"
assertContentContains "param1"

}

@Override
Class getDefaultClientType() {
APIClient
}
}

关于json - Grails 2.2 对需要请求 JSON 内容的远程 Web 服务的功能测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29307488/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com