检查 header 是否已分配给 Go unit-testing 中的请求

Check if the header has been assigned to the request in Go unit-testing

我正在尝试测试以下代码行:

httpReq.Header.Set("Content-Type", "application/json")

我正在以这种方式模拟对外部 api 的请求:

httpmock.RegisterResponder(http.MethodPost, "do-not-exist.com",
        httpmock.NewStringResponder(http.StatusOK, `{
            "data":{"Random": "Stuff"}}`),
    )

并想测试对 api 的请求是否具有我分配的 header。有什么办法可以实现吗?

response_test.go 说明了 header 是如何测试的:

        response, err := NewJsonResponse(200, test.body)
        if err != nil {
            t.Errorf("#%d NewJsonResponse failed: %s", i, err)
            continue
        }

        if response.StatusCode != 200 {
            t.Errorf("#%d response status mismatch: %d ≠ 200", i, response.StatusCode)
            continue
        }

        if response.Header.Get("Content-Type") != "application/json" {
            t.Errorf("#%d response Content-Type mismatch: %s ≠ application/json",
                i, response.Header.Get("Content-Type"))
            continue

您可以查看 table-driven test with httpmock.RegisterResponder here 的示例。

在@Kelsnare 的评论的帮助下,我能够通过以下方式解决这个问题:

    httpmock.RegisterResponder(http.MethodPost, "do-not-exist.com",
            func(req *http.Request) (*http.Response, error) {
                require.Equal(t, req.Header.Get("Content-Type"), "application/json")
                resp, _ := httpmock.NewStringResponder(http.StatusOK, `{
            "data":{"Random": "Stuff"}}`)(req)
                return resp, nil},
        )

我自己编写了 func 类型的 http.Responder 并在 func 中使用了 httpmock.NewStringResponder