Lesson 57 of 60 · Go
Testing HTTP Handlers – Table‑Driven Approach
Duration: 15 minutes
Table‑Driven Handler Tests
This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.
func TestHandlers(t *testing.T) {
tests := []struct {
name string
method string
path string
body string
wantStatus int
wantBody string
}{
{"GET hello", http.MethodGet, "/hello", "", http.StatusOK, "Hello, World!\n"},
{"POST echo", http.MethodPost, "/echo", "ping", http.StatusOK, "ping"},
}
// Setup router (could be chi, mux, etc.)
r := http.NewServeMux()
r.HandleFunc("/hello", helloHandler)
r.HandleFunc("/echo", echoHandler)
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
req := httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body))
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
resp := w.Result()
if resp.StatusCode != tc.wantStatus { t.Fatalf("status %d, want %d", resp.StatusCode, tc.wantStatus) }
b, _ := io.ReadAll(resp.Body)
if string(b) != tc.wantBody { t.Fatalf("body %q, want %q", b, tc.wantBody) }
})
}
}