A unit test that calls a live HTTP service can fail because the network or remote server is unavailable. Go’s standard-library `httptest` package provides local test infrastructure instead: a temporary server for testing an HTTP client, and a response recorder for testing a handler directly. section 6.5.4 section 8.2.1
ts := httptest.NewServer(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "...")
}))
defer ts.Close() #1
Create a server with `httptest.NewServer`, give it an `http.HandlerFunc` that writes a predictable response, pass `ts.URL` to the client under test, and close the server when the test ends. The client therefore needs a configurable URL rather than an exclusively hardcoded one. section 6.5.4
The same server handler can write an HTTP error status with `w.WriteHeader` to exercise a client’s failure path. This tests response handling without depending on the real exchange-rate endpoint. section 6.5.4
Listing 8.12 newgame/handler_test.go: Testing Handle
func TestHandle(t *testing.T) {
req, err := http.NewRequest(
http.MethodPost, "/games", nil) #1
require.NoError(t, err)
recorder := httptest.NewRecorder() #2
Handle(recorder, req) #3
assert.Equal(t, http.StatusCreated, recorder.Code) #4
assert.Equal(t, "application/json",
recorder.Header().Get("Content-Type")) #4
assert.JSONEq(t, `{"id":"",...}`,
recorder.Body.String()) #4
}
For a handler, build a request with `http.NewRequest`, pass an `httptest.NewRecorder()` to the handler, then inspect the recorded status code, headers, and body. Here the checks cover a created response and its JSON content. section 8.2.1
A recorder also works for a handler that produces HTML: check the recorded status, then compare the body with a fixture in `testdata`. Exact string equality is simple but brittle—an irrelevant whitespace change can fail the test. section 11.1.1



