Go Test Httptest Recorder
In this tutorial, you'll learn about Go Test: httptest.ResponseRecorder. We cover key concepts, practical examples, and best practices.
httptest.ResponseRecorder -- Use httptest.ResponseRecorder to test HTTP handlers without a server.
The Problem
http.ResponseRecorder implements http.ResponseWriter and captures the status code, headers, and body for assertion. No server startup needed.
Wrong
func TestHandler(t *testing.T) {
// Starting a full server just to test handler
server := httptest.NewServer(myHandler)
defer server.Close()
resp, _ := http.Get(server.URL)
Output:
// Works but heavier than needed for unit tests
Right
func TestHandler(t *testing.T) {
req := httptest.NewRequest("GET", "/api/user", nil)
rec := httptest.NewRecorder()
myHandler(rec, req)
resp := rec.Result()
if resp.StatusCode != 200 {
t.Errorf("got %d, want 200", resp.StatusCode)
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if string(body) != "expected" {
t.Errorf("got %s, want expected", body)
}
}
Output:
// Fast, no server, direct handler testing
Prevention
- Use httptest.NewRecorder() to capture response
- Use httptest.NewRequest() to create test requests
- No server needed, faster than httptest.NewServer
- Check status code, headers, body
- Use for unit testing handlers and middleware
Common Mistakes with test httptest recorder
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro