Failures and latency
Simulate dependencies that time out or respond slowly.
Timeouts
Timeout makes the mocked call fail with a timeout error. The client receives an error whose Timeout() method returns true, just as it would if the dependency stopped responding:
getUser := apitest.NewMock().
Get("http://users/api/user/1234").
RespondWith().
Status(http.StatusOK).
Body(`{"id": "1234", "name": "jon"}`).
End()
preferencesTimeout := apitest.NewMock().
Get("http://preferences/api/preferences/1234").
RespondWith().
Timeout().
End()
apitest.New().
Mocks(getUser, preferencesTimeout).
Handler(newUserAPI()).
Get("/user/1234").
Expect(t).
Status(http.StatusGatewayTimeout).
End()This is the reliable way to test timeout handling, because nothing has to wait.
Slow responses
FixedDelay waits the given number of milliseconds before responding. Delays are off by default, so a test opts in with EnableMockResponseDelay:
slowUser := apitest.NewMock().
Get("http://users/api/user/1234").
RespondWith().
Status(http.StatusOK).
Body(`{"id": "1234", "name": "jon"}`).
FixedDelay(250).
End()
apitest.New().
EnableMockResponseDelay().
Mocks(slowUser, getPreferencesMock).
Handler(newUserAPI()).
Get("/user/1234").
Expect(t).
Status(http.StatusOK).
End()Keeping delays off by default means shared mocks can carry realistic delays without slowing down every test that uses them. FixedDelay has no effect when Timeout is set.
The delay ignores client timeouts
The delay is a sleep before the response is returned. It does not observe the request context or the client's Timeout, so a client with a 50 millisecond timeout still receives a response from a mock with a 250 millisecond delay. Use Timeout to test timeout handling.
Error responses
Error statuses need nothing special. Respond with the status and body the dependency would send:
userNotFound := apitest.NewMock().
Get("http://users/api/user/9999").
RespondWith().
Status(http.StatusNotFound).
End()
apitest.New().
Mocks(userNotFound).
Handler(newUserAPI()).
Get("/user/9999").
Expect(t).
Status(http.StatusNotFound).
Body(`{"error": "user not found"}`).
End()