Skip to content

Lesson 7 of 9 · 23m

Test HTTP Services with httptest Before You Need a Browser

Use httptest.ResponseRecorder, httptest.Server, table tests, and realistic dependency seams to verify behavior at the transport boundary.

Go gives you a serious HTTP testing toolkit in the standard library, yet teams still test handlers by reading the code very carefully. httptest is not a toy. It exercises routing, middleware, encoding, status codes, cancellation plumbing, and client behavior without deploying anything. If you test only one layer, test the boundary where contracts are made.

Test handlers directly when speed matters

httptest.NewRecorder captures a response without binding a port:

func TestGetOrderNotFound(t *testing.T) {
    srv := NewServer(testLogger(), fakeStore{err: ErrNotFound}).routes()
    req := httptest.NewRequest(http.MethodGet, "/orders/ord_123", nil)
    rec := httptest.NewRecorder()

    srv.ServeHTTP(rec, req)

    if rec.Code != http.StatusNotFound {
        t.Fatalf("status = %d", rec.Code)
    }
}

This is ideal for validation, error mapping, authorization decisions, and middleware composition. It is fast enough that awkward cases stop being special occasions.

Use httptest.Server when transport behavior matters

A real listener exposes behavior a recorder cannot: chunked bodies, redirects, client cancellation, TLS, and real http.Client behavior:

upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    http.Error(w, "no", http.StatusBadGateway)
}))
defer upstream.Close()

client := NewDependencyClient(upstream.URL, upstream.Client())

Inject the generated URL rather than hard-coding ports. Fixed-port tests fight parallelism and leftovers.

Tables are for behavior matrices

Table tests work when cases truly share structure:

tests := []struct {
    name string
    body string
    want int
}{
    {"valid", `{"customer_id":"cus_1","sku":"sku_1","quantity":2}`, 201},
    {"bad quantity", `{"customer_id":"cus_1","sku":"sku_1","quantity":0}`, 400},
}

When cases need very different setup, split them. A clever table with five optional fields per case is a puzzle, not a test.

Build seams at interfaces you actually vary

Stores and dependency clients should be small interfaces or substitutable concrete types:

type OrderStore interface {
    Order(ctx context.Context, id string) (Order, error)
    Create(ctx context.Context, in CreateOrder) (Order, error)
}

A hand-written fake often reveals missing behavior in the interface. For outbound HTTP, prefer httptest.Server over mocks unless malformed wire behavior is the point.

Verify the contract, not only status

Assert meaningful JSON fields, important headers, and stable error codes. Avoid whole-response snapshots unless the format is intentionally frozen; snapshots are easy to update blindly during refactors.

Field notes

  • Add t.Parallel() only after checking for shared fakes, ports, environment variables, and globals.
  • Test unknown fields, trailing JSON, large bodies, wrong methods, and missing content types.
  • Recorders do not enforce real network behavior. Use both recorder and server tests.
  • If middleware ordering matters, test through the final composed handler.

Was this lesson helpful?

Sign in to rate