Body
Compare the response body as JSON or as an exact string.
JSON bodies
When the expected body is valid JSON, it is compared with the actual body structurally. Key order, whitespace and a trailing newline from json.Encoder make no difference:
apitest.Handler(handler).
Get("/user/1234").
Expect(t).
Status(http.StatusOK).
Body(`{
"name": "jon",
"is_contactable": true,
"id": "1234"
}`).
End()On a mismatch, the failure shows a diff of the decoded values. See reading a failure.
Other bodies
Any other body is compared as an exact string, so every character matters, including trailing newlines:
apitest.Handler(handler).
Get("/ping").
Expect(t).
Status(http.StatusOK).
Body("pong").
End()Formatted bodies
Bodyf formats the expected body with fmt.Sprintf, which helps when the body includes generated values:
apitest.Handler(handler).
Getf("/user/%s", id).
Expect(t).
Bodyf(`{"id": "%s", "name": "jon", "is_contactable": true}`, id).
End()Golden files
BodyFromFile reads the expected body from a file. JSON files are compared structurally, like Body:
apitest.Handler(handler).
Get("/user/1234").
Expect(t).
Status(http.StatusOK).
BodyFromFile("testdata/user.json").
End(){
"id": "1234",
"name": "jon",
"is_contactable": true
}Partial matches
Body compares the whole body. When the response contains values that change between runs, such as timestamps or generated IDs, assert on the stable parts with JSONPath, or write a custom assertion.