Testing HTTP handlers with httptest

A handler is a function, so it can be called directly with a request and a recorder instead of being sent over a socket. httptest.NewRecorder gives the response writer and httptest.NewRequest builds a request, which makes a handler test a unit test with no port, no goroutine and no network. The testing lesson covered the runner; this one tests the web layer.

A recorder instead of a socket

The recorder collects the status code, the headers and the body, and the test reads them after the handler returns. NewRequest sets the method, the URL and an optional body, and it accepts a target with a path and a query but no scheme or host, because the handler never opens a connection. A handler that reads a form or a JSON body gets it from the request the test built.

package api import ( "net/http" "net/http/httptest" "testing" ) func TestItems(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "/items", nil) rec := httptest.NewRecorder() Items(rec, req) if rec.Code != http.StatusOK { t.Fatalf("status = %d, want 200", rec.Code) } if got := rec.Header().Get("Content-Type"); got != "application/json" { t.Errorf("Content-Type = %q", got) } if body := rec.Body.String(); body == "" || body[0] != '[' { t.Errorf("body = %q, want a JSON array", body) } } func TestItemsWrongMethod(t *testing.T) { req := httptest.NewRequest(http.MethodPost, "/items", nil) rec := httptest.NewRecorder() Items(rec, req) if rec.Code != http.StatusMethodNotAllowed { t.Fatalf("status = %d, want 405", rec.Code) } if got := rec.Header().Get("Allow"); got != "GET" { t.Errorf("Allow = %q, want GET", got) } }

go test -v .

=== RUN TestItems
--- PASS: TestItems (0.00s)
=== RUN TestItemsWrongMethod
--- PASS: TestItemsWrongMethod (0.00s)
PASS
ok example.com/api 0.005s

The two tests checked the status, a header and the body, and the wrong-method test checked the Allow header the handler sets. That header is part of the contract: a caller that sent POST gets 405 and is told which method is allowed, and a test that does not check it will not notice when it disappears.

A table of requests

A table of paths and expected statuses covers the branches of a router without repeating the recorder setup. The request is built inside each subtest, so the cases share nothing and can be parallelised later. This is the same shape as the previous lesson, applied to HTTP: the input is a path, the output is a status.

package api import ( "net/http" "net/http/httptest" "testing" ) func TestItem(t *testing.T) { cases := []struct { name string path string status int }{ {"found", "/items/pen", http.StatusOK}, {"missing", "/items/paper", http.StatusNotFound}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { req := httptest.NewRequest(http.MethodGet, tc.path, nil) rec := httptest.NewRecorder() Item(rec, req) if rec.Code != tc.status { t.Errorf("%s status = %d, want %d", tc.path, rec.Code, tc.status) } }) } }

go test -v .

=== RUN TestItem
=== RUN TestItem/found
=== RUN TestItem/missing
--- PASS: TestItem (0.00s)
--- PASS: TestItem/found (0.00s)
--- PASS: TestItem/missing (0.00s)
PASS
ok example.com/api 0.006s

The found case returned 200 and the missing one 404 from http.NotFound. Note that the test calls the handler function directly, so it never exercises the mux that would route the path; a test of the routing belongs to a test of the server, not of the handler.

A real server for a client

httptest.NewServer starts an http.Server on a random port of the loopback interface and gives back a URL. It is the tool for testing a client, a middleware chain or anything that needs a real socket and a real response, and Close shuts it down. The port is chosen by the kernel, so two tests in parallel do not collide.

package api import ( "encoding/json" "net/http" "net/http/httptest" "testing" ) func TestItemsServer(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(Items)) defer srv.Close() resp, err := http.Get(srv.URL + "/items") if err != nil { t.Fatal(err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { t.Fatalf("status = %d", resp.StatusCode) } var got []item if err := json.NewDecoder(resp.Body).Decode(&got); err != nil { t.Fatal(err) } if len(got) != 2 || got[0].Name != "pen" { t.Errorf("decoded %+v", got) } }

go test -v .

=== RUN TestItemsServer
--- PASS: TestItemsServer (0.00s)
PASS
ok example.com/api 0.007s

The client fetched the URL the server printed, decoded the JSON and checked the first item. The defer srv.Close() line is as important as the request: a server that is not closed leaks a goroutine and a listener for the rest of the test binary, and the race detector may report it.

Exercises

  1. Add a handler that rejects a request without an Accept: application/json header with 406, and test both branches with a recorder.
  2. Turn the item table into parallel subtests with t.Parallel. What state would make that unsafe?
  3. Test a middleware that logs the status code by wrapping the recorder in a handler and checking the log output. Which writer does the middleware see?

Questions

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

  1. What does httptest.NewRecorder give a test?

    Answer

    A response writer that records the status, headers and body

    The recorder is the writer side; the handler writes into it and the test reads it.

  2. What does httptest.NewRequest need?

    Answer

    A method, a target path with optional query, and an optional body

    The handler does not open a connection, so a path is enough.

  3. Why is a handler test fast?

    Answer

    It calls the function directly, with no port and no network

    The recorder and the request are values; nothing is sent anywhere.

  4. What is httptest.NewServer for?

    Answer

    Testing a client or anything that needs a real socket

    It listens on a random loopback port and returns a URL.

  5. Why call srv.Close()?

    Answer

    It stops the listener and the goroutines the server started

    A leaked server keeps a port and a goroutine until the test binary exits.

  6. Which status does http.NotFound write?

    Answer

    404

    It writes the standard not-found response and status.

  7. What does the Allow header on a 405 tell the caller?

    Answer

    Which methods the resource accepts

    405 means the method is not allowed; Allow names the ones that are.

  8. What does the recorder's Body give?

    Answer

    The bytes the handler wrote, as a buffer the test can read

    It is a bytes.Buffer behind the ResponseWriter interface.

  9. What does a handler test NOT exercise when it calls the function directly?

    Answer

    The router and the server that would dispatch the request

    Routing needs a server or a mux test; the handler test covers the handler.

  10. Why is a random port useful in a test server?

    Answer

    Parallel tests do not collide and no port has to be configured

    The kernel picks a free port and the URL carries it.

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