httptest, fakes and mocks

A service has three kinds of dependency in a test: the HTTP layer that calls it, the storage behind it, and the other services beside it. Go has one tool for each shape and no framework that hides them: the httptest package for HTTP, an interface and a hand-written fake for storage, and a mock generator for the calls that must be checked one by one. The service below is small enough to show whole, and each section runs one way of testing it.

A handler with httptest

The service reads one note by id. The handler takes the id from the path with r.PathValue, which is the pattern syntax of Go 1.22, and writes JSON or a status code. Storage is an interface, so the service never knows what is behind it.

package notes import ( "encoding/json" "errors" "net/http" ) // ErrNotFound is returned when a note does not exist. var ErrNotFound = errors.New("note not found") // Note is one record of the service. type Note struct { ID string `json:"id"` Title string `json:"title"` } // Store keeps notes. type Store interface { Get(id string) (Note, error) Put(n Note) error } // Service reads notes through a Store. type Service struct { Store Store } // Handler returns the HTTP handler of the service. func (s *Service) Handler() http.Handler { mux := http.NewServeMux() mux.HandleFunc("GET /notes/{id}", s.get) return mux } func (s *Service) get(w http.ResponseWriter, r *http.Request) { n, err := s.Store.Get(r.PathValue("id")) if errors.Is(err, ErrNotFound) { http.Error(w, "note not found", http.StatusNotFound) return } if err != nil { http.Error(w, "internal error", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(n) }

The test calls the handler directly. httptest.NewRequest builds a *http.Request with a method, a URL and an optional body, and httptest.NewRecorder is a ResponseWriter that keeps the status, the headers and the body in memory. No socket is opened, no port is chosen and nothing can fail for a reason that is not the handler.

package notes import ( "net/http" "net/http/httptest" "strings" "testing" ) type fakeStore struct { notes map[string]Note err error } func (f *fakeStore) Get(id string) (Note, error) { if f.err != nil { return Note{}, f.err } n, ok := f.notes[id] if !ok { return Note{}, ErrNotFound } return n, nil } func (f *fakeStore) Put(n Note) error { if f.err != nil { return f.err } f.notes[n.ID] = n return nil } func TestGetNote(t *testing.T) { store := &fakeStore{notes: map[string]Note{"1": {ID: "1", Title: "milk"}}} srv := &Service{Store: store} req := httptest.NewRequest("GET", "/notes/1", nil) rec := httptest.NewRecorder() srv.Handler().ServeHTTP(rec, req) if rec.Code != http.StatusOK { t.Fatalf("status = %d, want 200", rec.Code) } if got, want := strings.TrimSpace(rec.Body.String()), `{"id":"1","title":"milk"}`; got != want { t.Errorf("body = %s, want %s", got, want) } if got := rec.Header().Get("Content-Type"); got != "application/json" { t.Errorf("Content-Type = %q, want application/json", got) } }

go test -trimpath -v -run TestGetNote$ ./notes

=== RUN TestGetNote
--- PASS: TestGetNote (0.00s)
PASS
ok example.com/notes/notes 0.005s

The three claims are the status, the body and the header, and each prints both values when it fails. var _ Store = (*fakeStore)(nil) is a compile-time assertion: if the interface gains a method, the test file stops compiling instead of the production file failing later.

Status codes in a table

The three answers of the handler are a found note, a missing one and a storage error, and the fake can produce all three because its error field is part of it. A table names each case once.

package notes import ( "errors" "net/http" "net/http/httptest" "testing" ) func TestGetNoteStatus(t *testing.T) { cases := []struct { name string store *fakeStore want int }{ {"found", &fakeStore{notes: map[string]Note{"1": {ID: "1", Title: "milk"}}}, http.StatusOK}, {"missing", &fakeStore{notes: map[string]Note{}}, http.StatusNotFound}, {"broken", &fakeStore{err: errors.New("disk on fire")}, http.StatusInternalServerError}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { rec := httptest.NewRecorder() req := httptest.NewRequest("GET", "/notes/1", nil) (&Service{Store: tc.store}).Handler().ServeHTTP(rec, req) if rec.Code != tc.want { t.Errorf("status = %d, want %d", rec.Code, tc.want) } }) } }

go test -trimpath -v -run TestGetNoteStatus ./notes

=== RUN TestGetNoteStatus
=== RUN TestGetNoteStatus/found
=== RUN TestGetNoteStatus/missing
=== RUN TestGetNoteStatus/broken
--- PASS: TestGetNoteStatus (0.00s)
--- PASS: TestGetNoteStatus/found (0.00s)
--- PASS: TestGetNoteStatus/missing (0.00s)
--- PASS: TestGetNoteStatus/broken (0.00s)
PASS
ok example.com/notes/notes 0.005s

The fake is a small map and one error field. It is not a mock: it has no expectations, records no calls and cannot fail because a method was called twice. That is the point of a fake, and it is why one fake can serve a whole package while every test with a mock tends to grow its own script.

A real socket with httptest.NewServer

Some behaviour only exists over a real connection: the client sends the headers, the server chooses the status text, a redirect follows a hop. httptest.NewServer starts the handler on a loopback port of the operating system and closes it at the end of the test.

package notes import ( "net/http" "net/http/httptest" "testing" ) func TestGetNoteOverHTTP(t *testing.T) { store := &fakeStore{notes: map[string]Note{"2": {ID: "2", Title: "bread"}}} srv := httptest.NewServer((&Service{Store: store}).Handler()) defer srv.Close() res, err := http.Get(srv.URL + "/notes/2") if err != nil { t.Fatal(err) } defer res.Body.Close() if res.StatusCode != http.StatusOK { t.Errorf("status = %d, want 200", res.StatusCode) } t.Logf("%s %s", res.Status, res.Header.Get("Content-Type")) }

go test -trimpath -v -run TestGetNoteOverHTTP ./notes

=== RUN TestGetNoteOverHTTP
server_test.go:22: 200 OK application/json
--- PASS: TestGetNoteOverHTTP (0.00s)
PASS
ok example.com/notes/notes 0.006s

The client is the ordinary http.Get, so the test exercises the same path a browser takes. The port is in srv.URL and changes every run; a test that printed the URL would print a different line each time, which is why the log above prints the status instead. httptest.NewTLSServer does the same with a certificate, for code that insists on https.

The fake

The fake in this page is a real implementation of the interface, and that is the property that makes it readable: a reader can say what it does without learning a framework. It cost twenty lines and no dependency. Its weakness is the opposite one: it cannot tell a test that calls Get once from one that calls it a hundred times, and a handler that reads the same note twice in a loop is a bug a fake will not report.

gomock

gomock generates the double from the interface, and the generated type records every call and compares it with the expectations. The generator is a program, so the mock is code a reader can inspect and the interface stays the only source of truth.

go run go.uber.org/mock/mockgen@v0.6.0 -source=notes/notes.go -destination=notes/mock_store_test.go -package=notes

The command writes about sixty lines: a MockStore with a controller, a recorder and one method per interface method. The test uses it like this:

package notes import ( "net/http" "net/http/httptest" "testing" "go.uber.org/mock/gomock" ) func TestGetNoteWithMock(t *testing.T) { ctrl := gomock.NewController(t) store := NewMockStore(ctrl) store.EXPECT().Get("1").Return(Note{ID: "1", Title: "milk"}, nil) rec := httptest.NewRecorder() req := httptest.NewRequest("GET", "/notes/1", nil) (&Service{Store: store}).Handler().ServeHTTP(rec, req) if rec.Code != http.StatusOK { t.Errorf("status = %d, want 200", rec.Code) } } func TestMockMissedCall(t *testing.T) { ctrl := gomock.NewController(t) store := NewMockStore(ctrl) store.EXPECT().Get("1").Return(Note{ID: "1", Title: "milk"}, nil) // The handler is never called, so the expectation is never met. }

go test -trimpath -v -run TestGetNoteWithMock ./notes

=== RUN TestGetNoteWithMock
--- PASS: TestGetNoteWithMock (0.00s)
PASS
ok example.com/notes/notes 0.005s

EXPECT() scripts the call, and the controller checks at the end of the test that the script was followed. The second test forgets to call the handler, which is exactly the failure a mock is for:

go test -trimpath -v -run TestMockMissedCall ./notes

=== RUN TestMockMissedCall
controller.go:97: missing call(s) to *notes.MockStore.Get(is equal to 1 (string)) example.com/notes/notes/mock_test.go:28
controller.go:97: aborting test due to missing call(s)
--- FAIL: TestMockMissedCall (0.00s)
FAIL
FAIL example.com/notes/notes 0.003s
FAIL

The message names the method, the argument it expected and the line that promised the call. A fake would have passed this test, because nothing in it checks that the store is read at all. That is the trade: a mock proves the interaction, and it makes the test depend on how the code talks to its dependency, so a refactor that keeps the behaviour and changes the calls breaks the test.

Fake or mock

Question Fake Mock
What does the double do? Returns real answers from simple data Records calls and compares them with a script
What does a passing test prove? The behaviour of the code under test The behaviour and the conversation with the dependency
What breaks in a refactor? Only a changed contract Every changed call, even when the outcome is the same
What does it cost? The lines a reader can see A generator, a dependency and a test that speaks in calls
Where it pays Storage, clocks, HTTP clients, anything with state A boundary that must be called exactly so, or not at all

The order the Go community usually recommends is: a fake first, a real implementation in an httptest server when the protocol matters, and a mock when the call itself is the contract. The lessons go deeper: testing HTTP handlers with httptest, fakes, stubs and interfaces and mocks: gomock and hand-written doubles.

The code on this page was run with go 1.26.10 and go.uber.org/mock v0.6.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev