1

I am trying to test the following line of code:

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

I am mocking the request to an external api in this way:

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

And want to test if the request to the api has the header that I assigned. Is there a way I could achieve this?

unitSphere
  • 241
  • 3
  • 17

2 Answers2

2

With the help of the comment by @Kelsnare I was able to solve this issue in the following way:

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

I wrote my own func of http.Responder type and used httpmock.NewStringResponder inside that func.

unitSphere
  • 241
  • 3
  • 17
0

response_test.go illustrates how the header is tested:

        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

You can see an example of table-driven test with httpmock.RegisterResponder here.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • Thanks for the answer. But isn't it checking the header of the response? I want to test if the request's header is set correctly – unitSphere Oct 06 '21 at 06:09
  • @Rustam Indeed, I was more on the response side with the mock library. Regarding the request side, do you mean like [this test](https://github.com/hashicorp/go-retryablehttp/blob/02c1586c8f14be23e7eeb522f1094afbabf45e93/client_test.go#L77-L81)? – VonC Oct 06 '21 at 06:13