liveBook · Manning

Httptest.ResponseRecorder

As explained in Learn Go with Pocket-Sized Projects

ResponseRecorder is a Go HTTP testing utility that records the status, headers, and body produced by a handler.

To test an HTTP handler without starting a server, create a request and pass an `httptest.NewRecorder()` to the handler as its response writer. The recorder lets the test inspect the status code, headers, and body the handler produced. section 8.2.1

Check a game-creation response

Create a POST request for `/games`, call `Handle(recorder, req)`, then check `recorder.Code` for `http.StatusCreated`, `recorder.Header().Get("Content-Type")` for `application/json`, and `recorder.Body.String()` for the expected JSON. Use `require.NoError` before continuing if request creation fails; use `assert` for response checks that can report multiple failures. section 8.2.1

A recorder also works when a unit test supplies route data directly. For a `/tick/` handler, set `habitID` with `req.SetPathValue`, call the handler, and inspect `rr.Result().StatusCode` and `rr.Body.String()`. This tests the handler with prepared data, not the router’s path-value extraction; testing the full request flow calls for an integration test. section 11.3.1

Listing 8.12 newgame/handler_test.go: Testing Handle
func TestHandle(t *testing.T) {
    req, err := http.NewRequest(
        http.MethodPost, "/games", nil) #1
    require.NoError(t, err)

    recorder := httptest.NewRecorder() #2

    Handle(recorder, req) #3

    assert.Equal(t, http.StatusCreated, recorder.Code) #4
    assert.Equal(t, "application/json", 
        recorder.Header().Get("Content-Type")) #4
    assert.JSONEq(t, `{"id":"",...}`,
        recorder.Body.String()) #4
}

The complete game-creation test shows the request, recorder, handler call, and status, header, and JSON assertions together. section 8.2.1

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Works through recorder setup and response assertions, then reuses it for a path-parameter test; does not examine recorder internals.
Examples
Checks a POST `/games` response and a `/tick/` response with a prepared path value.
What it assumes
Assumes familiarity with Go HTTP handlers and requests; demonstrates how to create the request and recorder used in the test.
What you can do after
Apply it via `httptest.NewRecorder` to assert handler status, headers, or body without running the service.
How it connects
Connects HTTP handlers, response writers, requests, status codes, JSON responses, redirects, and unit testing.

Also explained in

Compare how 2 books explain httptest.ResponseRecorder →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.