我已經成功地使用 Resty 在 Go 中設置了我的 API 自動化測試并執行了一個 GET 請求。然而,我正在努力讓 POST API 測試返回 200,而不是收到 400 錯誤消息。我不確定我做錯了什么。請在下面查看我的代碼。(順便說一下,POST 請求在 Postman 中工作?。ゝunc 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())}
1 回答

絕地無雙
TA貢獻1946條經驗 獲得超4個贊
您需要添加一個內容類型。這應該有效:
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")
- 1 回答
- 0 關注
- 152 瀏覽
添加回答
舉報
0/150
提交
取消