Debugging
Print every request and response on the wire, and inspect them programmatically.
Debug
Debug prints the wire representation of the request into the handler, every mocked call, and the final response:
apitest.New().
Debug().
Mocks(getUserMock, getPreferencesMock).
Handler(handler).
Get("/user/1234").
Expect(t).
Status(http.StatusOK).
End()----------> inbound http request
GET /user/1234 HTTP/1.1
Host: sut
----------> request to mock
GET /api/user/1234 HTTP/1.1
Host: users
User-Agent: Go-http-client/1.1
Authorization: Bearer s3cr3t
Accept-Encoding: gzip
<---------- response from mock
HTTP/1.1 200 OK
Content-Length: 29
Content-Type: application/json
{"id": "1234", "name": "jon"}
----------> request to mock
GET /api/preferences/1234 HTTP/1.1
Host: preferences
User-Agent: Go-http-client/1.1
Authorization: Bearer s3cr3t
Accept-Encoding: gzip
<---------- response from mock
HTTP/1.1 200 OK
Content-Length: 23
Content-Type: application/json
{"is_contactable":true}
<---------- final response
HTTP/1.1 200 OK
Connection: close
Content-Type: application/json
{"id":"1234","name":"jon","is_contactable":true}
Duration: 985.416µsWhen a call matches no mock, the output lists why each mock was rejected. See debugging a mismatch.
The output goes to standard output. go test shows it when the package fails, or always with -v.
Observe
Observe registers functions that receive the final response, the request, and the test once it has run. It gives programmatic access to the data Debug prints:
apitest.New().
Observe(func(res *http.Response, req *http.Request, a *apitest.APITest) {
t.Logf("%s %s -> %d", req.Method, req.URL, res.StatusCode)
observed = true
}).
Mocks(getUserMock, getPreferencesMock).
Handler(handler).
Get("/user/1234").
Expect(t).
Status(http.StatusOK).
End()Observers can make their own checks, for example on timing:
// fail any request that takes longer than 100ms end to end
started := time.Now()
apitest.New().
Observe(func(res *http.Response, req *http.Request, a *apitest.APITest) {
if elapsed := time.Since(started); elapsed > 100*time.Millisecond {
t.Errorf("%s %s took %s", req.Method, req.URL.Path, elapsed)
}
}).
Handler(handler).
Get("/health").
Expect(t).
Status(http.StatusOK).
End()Observe replaces any observers registered earlier on the test, and accepts several functions in one call. To observe mocked calls, use ObserveMocks.
Other tools
- Sequence diagrams give a visual record of a test, which is easier to scan than wire dumps.
Result.Responseholds the final response for inspection afterEnd(). See the result.