when — Actions
The testing/when package provides helpers for performing actions in tests — primarily HTTP requests.
HttpPostJSON
Makes an HTTP POST request with a JSON-encoded body.
- Marshals
*tto JSON - Posts to
urlwithContent-Type: application/json - Returns the raw
*http.Response
Example
type CreateListRequest struct {
Name string `json:"name"`
}
func (r CreateListRequest) MarshalJSON() ([]byte, error) {
return json.Marshal(struct{ Name string }{r.Name})
}
resp, err := when.HttpPostJSON(
server.URL+"/api/lists/my-list",
&CreateListRequest{Name: "Shopping"},
)
assert.NoError(t, err)
assert.Equal(t, http.StatusCreated, resp.StatusCode)
Note
In most tests, you will use the *resty.Client returned by given.FreshSetup directly, which provides a more ergonomic API. HttpPostJSON is a lower-level helper for cases where you need the raw *http.Response.
Resty Alternative
The resty.Client returned by given.FreshSetup is generally preferred: