Skip to content

Go Test Httptest Recorder

DodaTech 1 min read

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
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

  1. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  2. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  3. Using head and tail instead 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

**What methods does ResponseRecorder capture?**

Code, HeaderMap, Body bytes.

Can I use ResponseRecorder with middleware?

Yes. Pass it through middleware chain.

Does ResponseRecorder work with gin/echo context?

For Gin, use gin's test utilities. For Echo, use echo's test context.


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