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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With