如何在Go中测试http.NewRequest?

use*_*311 3 testing go

我大多熟悉Go中的测试,但很难找到测试以下功能的方法:

func postJson(url string, jsonData []byte) error {
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
    if err != nil {
        return err
    }
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        return err
    }
    resp.Body.Close()
    return nil
}
Run Code Online (Sandbox Code Playgroud)

我想检查请求是否有正确的帖子数据和正确的标题.试图查看httptests,但我不知道如何使用它.

mko*_*iva 5

httptest.Server有一个URL字段,可以使用该值来发送您的请求,那么这将是url自变量的函数.

然后,为了测试http.Request是否与正确的标题和正文一起发送,您可以在调用httptest.NewServer时使用自定义处理程序创建测试服务器.然后,服务器将在发送到上述url的每个请求上调用此处理程序,因此您的测试逻辑应该进入此处理程序.

ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    // Test that r is what you expect it to be
}))
defer ts.Close()

err := postJson(ts.URL+"/foo/bar", data)
Run Code Online (Sandbox Code Playgroud)

游乐场:https://play.golang.org/p/SldU4JSs911