Assertions
The result
Use the response after the test has run, and check which mocks were not called.
End() runs the test and returns an apitest.Result:
type Result struct {
Response *http.Response
// unexported fields
}
func (r Result) JSON(v any)
func (r Result) UnmatchedMocks() []UnmatchedMockDecoding the response
JSON decodes the response body into a value, for further checks in plain Go:
result := apitest.Handler(handler).
Get("/user/1234").
Expect(t).
Status(http.StatusOK).
End()
var user struct {
ID string `json:"id"`
Name string `json:"name"`
}
result.JSON(&user)
if user.Name != "jon" {
t.Errorf("unexpected user %+v", user)
}JSON reads the body, so call it once per result. It panics if the body cannot be read or is not valid JSON, which fails the test.
Chaining requests
A result can feed the next request, for example to fetch a resource using the ID returned when it was created:
var created struct {
ID string `json:"id"`
}
apitest.Handler(handler).
Post("/user").
JSON(`{"name": "ola"}`).
Expect(t).
Status(http.StatusCreated).
End().
JSON(&created)
apitest.Handler(handler).
Getf("/user/%s", created.ID).
Expect(t).
Status(http.StatusOK).
Bodyf(`{"id": "%s", "name": "ola"}`, created.ID).
End()The raw response
Result.Response is a copy of the response, with a readable body. Use it with your usual assertion library, or to read headers that are only known at run time.
Unmatched mocks
UnmatchedMocks lists the mocks that no request matched. See call counts.