api - 如何使用 Resty 创建自动化 API POST 测试请求
问题描述
我已经成功地使用 Resty 在 Go 中设置了我的 API 自动化测试并执行了一个 GET 请求。
然而,我正在努力让 POST API 测试返回 200,而不是收到 400 错误消息。我不确定我做错了什么。
请在下面查看我的代码。(顺便说一下,POST 请求在 Postman 中工作!)
func Test_Post(t *testing.T){
client := resty.New()
resp, _ := client.R().
SetBody(`{
"text": "Hello, I am learning how to test APIs with Postman!"
}`).
Post("https://api.funtranslations.com/translate/yoda")
assert.Equal(t, 200, resp.StatusCode())
}
解决方案
您需要添加一个内容类型。这应该有效:
func Test_Post(t *testing.T){
client := resty.New()
resp, _ := client.R().
SetBody(`{
"text": "Hello, I am learning how to test APIs with Postman!"
}`).
SetHeader("Content-Type", "application/json").
Post("https://api.funtranslations.com/translate/yoda")
assert.Equal(t, 200, resp.StatusCode())
}
如果您向客户端传递 json-serializable 数据类型而不是字符串,它将知道您打算发送 JSON,并正确设置标头:
resp, _ := client.R().
SetBody(map[string]string{
"text": "Hello, I am learning how to test APIs with Postman!",
}).
Post("https://api.funtranslations.com/translate/yoda")
推荐阅读
- assembly - 试图在 VS2017 ml64 中编译 x64 程序集,给出奇怪的语法错误
- sql-server - 在 SQL Server 中执行 bash 脚本
- android - 在 android studio 中创建原生库
- android - 带有标题的多级可扩展列表视图
- angular-ui-router - Angular:未检测到子路由
- python - BeautifulSoup 提取脚本变量数据
- facebook - 如何在通过 Facebook Messenger 打开的 webview 中通过摄像头上传文件?
- java - 在泛型声明中使用“?扩展”时,可以避免 Java 中的参数不匹配吗?
- reactjs - LibraryManagedAttributes 未映射元素类型
- cloudkit - CloudKit - 如何使用 CKModifyRecordsOperation 检索刚刚保存的记录的 ckRecordID