【问题标题】:How do you create an automation API POST test request using Resty如何使用 Resty 创建自动化 API POST 测试请求
【发布时间】:2020-12-07 00:06:35
【问题描述】:

我已经成功地使用 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())
}

【问题讨论】:

    标签: api go automated-tests


    【解决方案1】:

    您需要添加一个 Content-Type。这应该有效:

    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,并正确设置 header:

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

    【讨论】:

    • 非常感谢它现在确实有效感谢快速响应
    猜你喜欢
    • 2018-04-13
    • 2019-06-16
    • 2021-12-26
    • 2016-01-24
    • 1970-01-01
    • 2017-09-10
    • 2012-06-22
    • 1970-01-01
    • 2016-01-05
    相关资源
    最近更新 更多