user9180311
user9180311

Reputation: 61

How can I test the http.NewRequest in Go?

I am mostly familiar with testing in Go, but struggling to find a way to test the following function:

func postJson(url string, jsonData []byte) error {
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
    if err != nil {
        return err
    }
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        return err
    }
    resp.Body.Close()
    return nil
}

I want to check that the request has correct post data with the right headers. Tried to look into httptests, but I am not sure how to use it.

Upvotes: 6

Views: 3274

Answers (1)

mkopriva
mkopriva

Reputation: 38233

The httptest.Server has a URL field, you can use that value to send your requests to, so this would be the url argument to your function.

Then to test whether the http.Request was sent with the right headers and body you can create the test server with a custom handler when calling httptest.NewServer. This handler will then be invoked by the server on each request that is sent to the url mentioned above, so your test logic should go inside this handler.

ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    // Test that r is what you expect it to be
}))
defer ts.Close()

err := postJson(ts.URL+"/foo/bar", data)

Playground:https://play.golang.org/p/SldU4JSs911

Upvotes: 5

Related Questions