Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test the http.NewRequest in Go?

Tags:

testing

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.

like image 582
user9180311 Avatar asked Jan 06 '18 06:01

user9180311


People also ask

How do I test my go code?

At the command line in the greetings directory, run the go test command to execute the test. The go test command executes test functions (whose names begin with Test ) in test files (whose names end with _test.go). You can add the -v flag to get verbose output that lists all of the tests and their results.

How do I send a post request in go?

Go HTTP POST request FORM data The Content-Type header is set to application/x-www-form-urlencoded. The data is sent in the body of the request; the keys and values are encoded in key-value tuples separated by '&', with a '=' between the key and the value. We send a POST request to the https://httpbin.org/post page.

What is HTTP Go client?

Golang HTTP Performance. HTTP (hypertext transfer protocol) is a communication protocol that transfers data between client and server. HTTP requests are very essential to access resources from the same or remote server.


1 Answers

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

like image 84
mkopriva Avatar answered Nov 13 '22 12:11

mkopriva