Capstone 3: httptest and a fake store

The API tests run the same handler the server runs, against a fake store, with a real HTTP client and httptest.NewServer. They check the status, the error shape and the JSON validity of every answer, and they never touch a socket on a fixed port, a file or a database. The whole suite takes ten milliseconds.

The fake store

The fake is the interface from lesson 130 with a map and a counter, plus a fail flag that makes List return an error, which is how the 500 path gets covered without a broken disk. The id order is by increasing id, matching the real store.

package api import ( "bytes" "encoding/json" "io" "log/slog" "net/http" "net/http/httptest" "strings" "testing" "example.com/notesapi/internal/store" ) type fakeStore struct { notes map[int]store.Note next int fail bool } func newFakeStore() *fakeStore { return &fakeStore{notes: map[int]store.Note{}, next: 1} } func (f *fakeStore) List() ([]store.Note, error) { if f.fail { return nil, store.ErrNotFound } out := make([]store.Note, 0, len(f.notes)) for i := 1; i <= f.next; i++ { if note, ok := f.notes[i]; ok { out = append(out, note) } } return out, nil } func (f *fakeStore) Get(id int) (store.Note, error) { note, ok := f.notes[id] if !ok { return store.Note{}, store.ErrNotFound } return note, nil } func (f *fakeStore) Create(title string) (store.Note, error) { if strings.TrimSpace(title) == "" { return store.Note{}, store.ErrEmptyTitle } note := store.Note{ID: f.next, Title: title} f.next++ f.notes[note.ID] = note return note, nil } func (f *fakeStore) Update(id int, title string, done bool) (store.Note, error) { note, ok := f.notes[id] if !ok { return store.Note{}, store.ErrNotFound } if strings.TrimSpace(title) == "" { return store.Note{}, store.ErrEmptyTitle } note.Title = title note.Done = done f.notes[id] = note return note, nil } func (f *fakeStore) Delete(id int) error { if _, ok := f.notes[id]; !ok { return store.ErrNotFound } delete(f.notes, id) return nil } func discardLogger() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) } func TestAPI(t *testing.T) { srv := httptest.NewServer(New(newFakeStore(), discardLogger()).Routes()) defer srv.Close() call := func(method, path, body string) (int, string) { req, err := http.NewRequest(method, srv.URL+path, bytes.NewBufferString(body)) if err != nil { t.Fatal(err)

The logger is a handler over io.Discard, so a test does not print log lines and does not need a *testing.T in the constructor. A test that wants to assert a line uses a buffer, the same trick as lesson 92.

The table

Eleven cases, each a method, a path, an optional body, a status and a substring the body must contain. The cases run in order against one server, so the create makes the note the get reads. A t.Run per case names the failure, and a body that is not valid JSON fails every case that expects JSON, including the list.

if body != "" { req.Header.Set("Content-Type", "application/json") } resp, err := http.DefaultClient.Do(req) if err != nil { t.Fatal(err) } defer resp.Body.Close() data, err := io.ReadAll(resp.Body) if err != nil { t.Fatal(err) } return resp.StatusCode, string(data) } tests := []struct { name string method string path string body string status int want string }{ {"health", "GET", "/healthz", "", 200, `"status":"ok"`}, {"create", "POST", "/api/notes", `{"title":"buy milk"}`, 201, `"id":1`}, {"get", "GET", "/api/notes/1", "", 200, `"title":"buy milk"`}, {"update", "PUT", "/api/notes/1", `{"title":"buy milk","done":true}`, 200, `"done":true`}, {"list", "GET", "/api/notes", "", 200, `"done":true`}, {"delete", "DELETE", "/api/notes/1", "", 204, ""}, {"missing", "GET", "/api/notes/9", "", 404, `"note not found"`}, {"empty title", "POST", "/api/notes", `{"title":" "}`, 400, `"title is required"`}, {"bad json", "POST", "/api/notes", `{"title":`, 400, `"invalid JSON body"`}, {"unknown field", "POST", "/api/notes", `{"title":"x","color":"red"}`, 400, `"invalid JSON body"`}, {"wrong method", "POST", "/api/notes/1", `{}`, 405, ""}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { status, body := call(tt.method, tt.path, tt.body) if status != tt.status { t.Errorf("status = %d, want %d (body %s)", status, tt.status, body) } if tt.want != "" && !strings.Contains(body, tt.want) { t.Errorf("body %q does not contain %q", body, tt.want) } if tt.status != 204 && tt.status != 405 && !json.Valid([]byte(body)) { t.Errorf("body is not JSON: %q", body) } }) } } func TestAPIStoreFailure(t *testing.T) { srv := httptest.NewServer(New(&fakeStore{fail: true}, discardLogger()).Routes()) defer srv.Close() resp, err := http.Get(srv.URL + "/api/notes") if err != nil { t.Fatal(err) } defer resp.Body.Close() if resp.StatusCode != http.StatusInternalServerError { t.Fatalf("status = %d, want 500", resp.StatusCode) } }

The 405 case is the exception to the JSON check, because the answer comes from the mux and is plain text; the test asserts the status and lets the body be. That is a real fact about the standard library, and a test that hid it would fail on the next Go release.

The run

go test -count=1 -v ./internal/api runs the table and the failure test. The subtests are named after the case, so a red line points at one request.

go test -count=1 -v ./internal/api

=== RUN TestAPI
=== RUN TestAPI/health
=== RUN TestAPI/create
=== RUN TestAPI/get
=== RUN TestAPI/update
=== RUN TestAPI/list
=== RUN TestAPI/delete
=== RUN TestAPI/missing
=== RUN TestAPI/empty_title
=== RUN TestAPI/bad_json
=== RUN TestAPI/unknown_field
=== RUN TestAPI/wrong_method
--- PASS: TestAPI (0.00s)
--- PASS: TestAPI/health (0.00s)
--- PASS: TestAPI/create (0.00s)
--- PASS: TestAPI/get (0.00s)
--- PASS: TestAPI/update (0.00s)
--- PASS: TestAPI/list (0.00s)
--- PASS: TestAPI/delete (0.00s)
--- PASS: TestAPI/missing (0.00s)
--- PASS: TestAPI/empty_title (0.00s)
--- PASS: TestAPI/bad_json (0.00s)
--- PASS: TestAPI/unknown_field (0.00s)
--- PASS: TestAPI/wrong_method (0.00s)
=== RUN TestAPIStoreFailure
--- PASS: TestAPIStoreFailure (0.00s)
PASS
ok example.com/notesapi/internal/api 0.010s

Twelve cases pass in ten milliseconds. The run is a documentation of the contract: a reader can see every status the API promises without starting the service.

A failing store

The failure test sets the flag, requests the list and expects a 500. It is the case a happy-path table never reaches, and it is where the handler that forgot to map a store error would be caught. The response body is the error shape, not the store's message: the internal error is for the log.

What the tests hold

The tests hold the HTTP contract and the handler mapping, with the store and the logger replaced. They do not hold the real store, the real listener or the shutdown; those are covered by one end-to-end run with the file store and by the deploy lesson. The split is the usual one: many fast tests at the seam, one slow test of the wiring.

The next lesson serves the built frontend from the same binary.

Exercises

  1. Add a case for a title of only spaces. Which status does it expect, and which handler line produces it?
  2. Add a case that checks the X-Request-ID header is present. Which middleware sets it, and what does the test need to see it?
  3. Replace the fake store with the file store in the table and run it in a temporary directory. Which tests become slower, and what does the table no longer need?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does httptest.NewServer give the API tests?

    Answer

    A real HTTP server and client on a free port

    The middleware runs for real.

  2. What does the fake store add to the interface?

    Answer

    A fail flag for the error path

    It reaches the 500 case.

  3. Which cases does the table run against one server?

    Answer

    The listed ones in order, so state carries

    The create makes the note the get reads.

  4. Why is the body checked with json.Valid?

    Answer

    Every answer except 405 must be JSON

    The 405 is the mux text.

  5. What does the failure test expect?

    Answer

    A 500 with the error shape

    The store error is internal.

  6. Why a logger over io.Discard?

    Answer

    The test does not print and needs no *testing.T

    A buffer is for asserting.

  7. What do the tests not cover?

    Answer

    The real store, the listener and the shutdown

    One end-to-end run covers the wiring.

  8. Why does the 405 body not have to be JSON?

    Answer

    The mux writes plain text for it

    The test asserts the status only.

  9. What does the table name on a failure?

    Answer

    The case through t.Run

    A red line points at one request.

  10. What is the next lesson?

    Answer

    Serving the built frontend from the binary

    The embed lesson.

The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image