typestar

Testing an HTTP handler in Go

httptest gives a recorder and a request, so no port is opened.

func healthz(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)
    fmt.Fprint(w, `{"status":"ok"}`)
}

func TestHealthz(t *testing.T) {
    request := httptest.NewRequest(http.MethodGet, "/healthz", nil)
    recorder := httptest.NewRecorder()

    healthz(recorder, request)

    if recorder.Code != http.StatusOK {
        t.Fatalf("status = %d, want 200", recorder.Code)
    }
    if got := recorder.Header().Get("Content-Type"); got != "application/json" {
        t.Errorf("content type = %q", got)
    }
    if !strings.Contains(recorder.Body.String(), `"ok"`) {
        t.Errorf("body = %q", recorder.Body.String())
    }
}

How it works

  1. NewRequest builds the request in memory.
  2. NewRecorder captures the status, headers and body.
  3. httptest.NewServer is for testing a client instead.

Keywords and builtins used here

The run, in numbers

Lines
22
Characters to type
637
Tokens
161
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 92 seconds.

Type this snippet

Step 2 of 3 in Fakes & fixtures, step 6 of 13 in Testing.

← Previous Next →