Mocks
Responses
Set the status, headers, cookies and body a mock returns.
getUser := apitest.NewMock().
Get("http://users/api/user/1234").
RespondWith().
Status(http.StatusOK).
Header("Cache-Control", "no-store").
Headers(map[string]string{"X-Request-Id": "abc"}).
Cookie("session", "12345").
Cookies(apitest.NewCookie("theme").Value("dark").Path("/")).
Bodyf(`{"id": "%s", "name": "jon"}`, "1234").
End()| Method | Sets |
|---|---|
Status(code) | The status code. Defaults to 0, so always set it. |
Header(key, value) | Adds a header value. |
Headers(map[string]string) | Adds a header value for each entry. |
Cookie(name, value) | Adds a Set-Cookie header. |
Cookies(...*apitest.Cookie) | Adds a Set-Cookie header per cookie, with any attributes you set. |
Body(s) | The body. |
Bodyf(format, args...) | The body, formatted with fmt.Sprintf. |
JSON(v) | The body. Strings and byte slices are used as is, and other values are marshalled. |
BodyFromFile(path) | The body, read from a file. |
Content type
When the body is not empty and no Content-Type header is set, the mock sets one: application/json when the body is valid JSON, and text/plain otherwise. Set the header yourself for anything else, such as application/problem+json.
Bodies from files
Recorded responses from the real service make realistic fixtures:
getUser := apitest.NewMock().
Get("http://users/api/user/1234").
RespondWith().
Status(http.StatusOK).
BodyFromFile("testdata/user.json").
End()Errors and delays
The response side also controls how the call behaves: Timeout makes it fail with a timeout, FixedDelay makes it slow, and Times and AnyTimes control how many calls the mock answers. See failures and latency and call counts.