apitest
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 Status the status code is not checked, and with no Body the 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 Assert functions 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()
AssertionPasses for
apitest.IsSuccess200 to 399
apitest.IsClientError400 to 499
apitest.IsServerError500 and above

In this section

On this page