Test Go handlers with httptest, fake repositories, JSON assertions, and table-driven status cases.
7 min readBuilding Backend ApplicationsBuild
Handler Testing Pattern
Handler tests use httptest to create fake requests and record responses. Fake repositories eliminate external dependencies. This makes handler tests fast, deterministic, and independent of infrastructure.
Gohandler-test-setup.go
19 linesLn 1, Col 1Go
Create a fake repository with test data. Inject it into the handler. Use httptest to send a request and capture the response. Assert the status code and body.
Fake Repositories
Gofake-repository-implementation.go
28 linesLn 1, Col 1Go
Fake repositories implement the same interface as real repositories. They store data in memory. SetError lets you simulate database failures. This makes tests fast and controllable.
Table-Driven Tests
Gotable-driven-handler-tests.go
29 linesLn 1, Col 1Go
Table-driven tests cover all error paths. Each case specifies the input, expected status, and expected error message. This catches missing validation and incorrect error handling.
JSON Assertions
Goasserting-json-responses.go
26 linesLn 1, Col 1Go
Decode the JSON response and compare individual fields. Use t.Helper() for clean error messages. This catches serialization bugs and missing fields.
Testing Middleware
Gomiddleware-unit-tests.go
34 linesLn 1, Col 1Go
Test middleware independently by wrapping a simple next handler. Verify that middleware correctly allows or rejects requests based on input.
Testing Errors
Gotesting-error-responses.go
21 linesLn 1, Col 1Go
Test that repository errors produce the correct HTTP status code. Verify the error response body does not leak internal details.
Use testify for assertions
The testify package provides assert and require for cleaner test assertions. assert.Equal(t, expected, actual) is more readable than manual comparison.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.