Go Web Expert
Comprehensive Go web development persona enforcing zero global state, explicit error handling, input validation, testability, and documentation conventions....
Documentation & Preview
Testing Go HTTP Handlers
httptest Fundamentals
Every handler test follows the same three-step pattern: build a request, record the response, assert on the result.
Basic Pattern
func TestServer_handleHealth(t *testing.T) {
srv := NewServer(nil, slog.Default())
req := httptest.NewRequest("GET", "/healthz", nil)
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want %d", w.Code, http.StatusOK)
}
}httptest.NewRequest vs http.NewRequest
// httptest.NewRequest -- panics on error, never returns one.
// Use in tests where a bad URL is a programming error.
req := httptest.NewRequest("GET", "/api/users/123", nil)
// http.NewRequest -- returns an error. Use when constructing
// from dynamic test data that could be invalid.
req, err := http.NewRequest("POST", "/api/users", body)
if err != nil {
t.Fatal(err)
}httptest.NewRecorder
httptest.NewRecorder returns a *httptest.ResponseRecorder that implements http.ResponseWriter and captures everything the handler writes.
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
w.Code // status code (int)
w.Body.String() // response body as string
w.Body.Bytes() // response body as []byte
w.Header().Get("Content-Type") // response headers
w.Result() // *http.Response for more detailed inspection---
Testing with Real JSON Payloads
POST with JSON Body
func TestServer_handleCreateUser(t *testing.T) {
mockStore := &MockUserStore{
CreateFunc: func(ctx context.Context, u *User) error {
u.ID = "generated-id"
return nil
},
}
srv := NewServer(mockStore, slog.Default())
body := strings.NewReader(`{"name":"Alice","email":"alice@example.com"}`)
req := httptest.NewRequest("POST", "/api/users", body)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code != http.StatusCreated {
t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusCreated, w.Body.String())
}
var resp User
if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
t.Fatalf("decoding response: %v", err)
}
if resp.ID == "" {
t.Error("expected non-empty user ID")
}
if resp.Name != "Alice" {
t.Errorf("name = %q, want %q", resp.Name, "Alice")
}
}Testing Validation Errors
func TestServer_handleCreateUser_validation(t *testing.T) {
srv := NewServer(&MockUserStore{}, slog.Default())
tests := []struct {
name string
body string
wantStatus int
wantErr string
}{
{
name: "missing name",
body: `{"email":"alice@example.com"}`,
wantStatus: 422,
wantErr: "name",
},
{
name: "invalid email",
body: `{"name":"Alice","email":"not-an-email"}`,
wantStatus: 422,
wantErr: "email",
},
{
name: "malformed JSON",
body: `{bad json`,
wantStatus: 400,
wantErr: "invalid JSON",
},
{
name: "empty body",
body: ``,
wantStatus: 400,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest("POST", "/api/users", strings.NewReader(tt.body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code != tt.wantStatus {
t.Errorf("status = %d, want %d; body = %s", w.Code, tt.wantStatus, w.Body.String())
}
if tt.wantErr != "" && !strings.Contains(w.Body.String(), tt.wantErr) {
t.Errorf("body = %q, want to contain %q", w.Body.String(), tt.wantErr)
}
})
}
}Decoding JSON Responses with a Helper
func decodeJSON[T any](t *testing.T, w *httptest.ResponseRecorder) T {
t.Helper()
var result T
if err := json.NewDecoder(w.Body).Decode(&result); err != nil {
t.Fatalf("decoding response body: %v", err)
}
return result
}
// Usage
resp := decodeJSON[User](t, w)
if resp.Name != "Alice" {
t.Errorf("name = %q, want %q", resp.Name, "Alice")
}---
Testing Middleware Chains
Testing a Single Middleware
Test middleware in isolation by wrapping a known inner handler:
func TestRequestIDMiddleware(t *testing.T) {
// Inner handler that captures the request ID from context
var gotID string
inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotID = RequestIDFromContext(r.Context())
w.WriteHeader(http.StatusOK)
})
handler := RequestID(inner)
t.Run("generates ID when missing", func(t *testing.T) {
req := httptest.NewRequest("GET", "/", nil)
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
if gotID == "" {
t.Error("expected non-empty request ID in context")
}
if w.Header().Get("X-Request-ID") == "" {
t.Error("expected X-Request-ID response header")
}
})
t.Run("preserves existing ID", func(t *testing.T) {
req := httptest.NewRequest("GET", "/", nil)
req.Header.Set("X-Request-ID", "test-id-123")
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
if gotID != "test-id-123" {
t.Errorf("request ID = %q, want %q", gotID, "test-id-123")
}
})
}Testing the Full Middleware Stack
Test through the complete stack to verify middleware ordering and interaction:
func TestMiddlewareChain(t *testing.T) {
mockStore := &MockUserStore{
GetUserFunc: func(ctx context.Context, id string) (*User, error) {
return &User{ID: id, Name: "Alice"}, nil
},
}
srv := NewServer(mockStore, slog.Default())
// Apply the same middleware stack as production
handler := Chain(srv, Recovery, RequestID, Logger(slog.Default()))
req := httptest.NewRequest("GET", "/api/users/123", nil)
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want %d", w.Code, http.StatusOK)
}
if w.Header().Get("X-Request-ID") == "" {
t.Error("middleware chain did not set X-Request-ID")
}
}Testing Recovery Middleware
func TestRecoveryMiddleware(t *testing.T) {
panicking := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
panic("something went wrong")
})
handler := Recovery(panicking)
req := httptest.NewRequest("GET", "/", nil)
w := httptest.NewRecorder()
// Should not panic
handler.ServeHTTP(w, req)
if w.Code != http.StatusInternalServerError {
t.Errorf("status = %d, want %d", w.Code, http.StatusInternalServerError)
}
}---
Testing Authentication and Authorization
Testing Auth Middleware
func TestAuthMiddleware(t *testing.T) {
inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, ok := UserFromContext(r.Context())
if !ok {
t.Fatal("expected user in context")
}
fmt.Fprintf(w, "hello %s", user.Name)
})
tokenValidator := &MockTokenValidator{
ValidateFunc: func(token string) (*User, error) {
if token == "Bearer valid-token" {
return &User{ID: "1", Name: "Alice", Roles: []string{"admin"}}, nil
}
return nil, errors.New("invalid token")
},
}
handler := AuthMiddleware(tokenValidator)(inner)
tests := []struct {
name string
authHeader string
wantStatus int
wantBody string
}{
{
name: "valid token",
authHeader: "Bearer valid-token",
wantStatus: http.StatusOK,
wantBody: "hello Alice",
},
{
name: "invalid token",
authHeader: "Bearer bad-token",
wantStatus: http.StatusUnauthorized,
},
{
name: "missing header",
authHeader: "",
wantStatus: http.StatusUnauthorized,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest("GET", "/", nil)
if tt.authHeader != "" {
req.Header.Set("Authorization", tt.authHeader)
}
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
if w.Code != tt.wantStatus {
t.Errorf("status = %d, want %d", w.Code, tt.wantStatus)
}
if tt.wantBody != "" && !strings.Contains(w.Body.String(), tt.wantBody) {
t.Errorf("body = %q, want to contain %q", w.Body.String(), tt.wantBody)
}
})
}
}Testing Role-Based Authorization
func TestRequireRole(t *testing.T) {
inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
handler := RequireRole("admin")(inner)
tests := []struct {
name string
user *User
wantStatus int
}{
{
name: "admin user",
user: &User{Roles: []string{"admin"}},
wantStatus: http.StatusOK,
},
{
name: "regular user",
user: &User{Roles: []string{"user"}},
wantStatus: http.StatusForbidden,
},
{
name: "no user in context",
user: nil,
wantStatus: http.StatusUnauthorized,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest("GET", "/admin", nil)
if tt.user != nil {
ctx := context.WithValue(req.Context(), userKey, tt.user)
req = req.WithContext(ctx)
}
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
if w.Code != tt.wantStatus {
t.Errorf("status = %d, want %d", w.Code, tt.wantStatus)
}
})
}
}---
Integration Tests with Real Database
Pattern: Test Database with t.Cleanup
func setupTestDB(t *testing.T) *sql.DB {
t.Helper()
dsn := os.Getenv("TEST_DATABASE_URL")
if dsn == "" {
t.Skip("TEST_DATABASE_URL not set")
}
db, err := sql.Open("postgres", dsn)
if err != nil {
t.Fatalf("opening test database: %v", err)
}
t.Cleanup(func() {
db.Close()
})
return db
}Transaction Rollback for Test Isolation
Each test runs in a transaction that is rolled back, leaving the database unchanged:
func setupTestTx(t *testing.T, db *sql.DB) *sql.Tx {
t.Helper()
tx, err := db.Begin()
if err != nil {
t.Fatalf("beginning transaction: %v", err)
}
t.Cleanup(func() {
tx.Rollback() // always rollback -- test data never persists
})
return tx
}Full Integration Test
func TestUserStore_Integration(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
db := setupTestDB(t)
tx := setupTestTx(t, db)
store := NewUserStore(tx)
t.Run("create and retrieve", func(t *testing.T) {
user := &User{Name: "Alice", Email: "alice@example.com"}
err := store.Create(context.Background(), user)
if err != nil {
t.Fatalf("creating user: %v", err)
}
if user.ID == "" {