Assertions
Asserting on responses
How expectations are checked, and how to assert on the status code.
Expect(t) ends the request and starts the expectations. Each expectation method adds a check, and End() sends the request and runs them.
apitest.Handler(handler).
Get("/user/1234").
Expect(t).
Status(http.StatusOK).
Header("Content-Type", "application/json").
Headers(map[string]string{"X-Request-Id": "12345"}).
HeaderPresent("Etag").
HeaderNotPresent("X-Powered-By").
End()How expectations run
- Only what you set is checked. With no
Statusthe status code is not checked, and with noBodythe body is not checked. - Every failure is reported. Failed checks call
t.Errorf, so one run reports every mismatch rather than stopping at the first. - Checks run in a fixed order. Mock call counts come first, then the status, body, headers, cookies, and finally custom
Assertfunctions in the order they were added.
Status
Status asserts on the status code. Use the net/http constants for readability:
apitest.Handler(handler).
Get("/user/1234").
Expect(t).
Status(http.StatusOK).
End()To accept a range of codes, use one of the ready-made assertions with Assert:
apitest.Handler(handler).
Get("/user/1234").
Expect(t).
Assert(apitest.IsSuccess).
End()| Assertion | Passes for |
|---|---|
apitest.IsSuccess | 200 to 399 |
apitest.IsClientError | 400 to 499 |
apitest.IsServerError | 500 and above |