1

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

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

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

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

并想测试对 api 的请求是否具有我分配的标头。有没有办法我可以做到这一点?

4

2 回答 2

1

在@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},
        )

我写了自己funchttp.Responder类型并httpmock.NewStringResponder在里面使用func

于 2021-10-06T06:44:30.467 回答
0

response_test.go说明如何测试标头:

        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

您可以在此处查看表驱动测试httpmock.RegisterResponder的示例。

于 2021-10-06T05:56:43.267 回答