Skip to content

HTTP Handler Testing

Learn to test HTTP handlers without starting a real server using httptest.

Recommended Prerequisites

Complete these exercises first for the best learning experience:

  • Table-Driven Tests

0/1 completed

The httptest package provides tools for testing HTTP code without network overhead:

  • httptest.NewRequest: Creates test HTTP requests
  • httptest.NewRecorder: Captures handler responses (status, headers, body)

You can test handlers directly by calling them with a recorder and request, making tests fast and deterministic.

Test an API server with user endpoints:

  1. Test GET request for existing user (200 OK)
  2. Test GET request for missing user (404 Not Found)
  3. Test POST request to create user (201 Created)
  4. Test POST request with invalid JSON (400 Bad Request)
  5. Verify response status codes, headers, and body content

HTTP Handler Testing with httptest

~25 minmedium

Test HTTP handlers using httptest.NewRequest and NewRecorder

  • httptest.NewRequest: Create test HTTP requests without network
  • httptest.NewRecorder: Capture handler responses (status, headers, body)
  • Direct Handler Testing: Call handlers directly with recorder and request
  • Status Code Testing: Verify correct HTTP status codes (200, 404, 400, 201)
  • Response Validation: Check both status and body content in tests