【问题标题】:Check if the header has been assigned to the request in Go unit-testing检查标头是否已分配给 Go 单元测试中的请求
【发布时间】:2021-11-26 06:30:40
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 你能不能不使用自己的func httpmock.Responder 类型并在里面检查它 - 而不是使用httpmock.NewStringResponder
  • 你是对的。非常感谢您的评论!

标签: go go-http go-testing


【解决方案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},
        )

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

【讨论】:

  • 干得好。赞成。
【解决方案2】:

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

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

【讨论】:

  • 感谢您的回答。但它不是在检查响应的标题吗?我想测试请求的标头是否设置正确
  • @Rustam 的确,我在模拟库的响应方面更多。关于请求方,你的意思是像this test吗?
猜你喜欢
  • 2012-03-05
  • 2021-12-19
  • 1970-01-01
  • 2020-07-29
  • 1970-01-01
  • 1970-01-01
  • 2021-09-29
  • 2014-07-08
  • 2021-09-13
相关资源
最近更新 更多