首页 > 解决方案 > 如何使用 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())
}

标签: apigoautomated-tests

解决方案


您需要添加一个内容类型。这应该有效:

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")

推荐阅读