Search code examples
gogo-httpgo-testing

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


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?


Solution

  • 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.