liveBook · Manning

Httptest

As explained in Learn Go with Pocket-Sized Projects

httptest is Go's standard-library package for testing HTTP clients and servers with in-memory or local test infrastructure.

A unit test that calls a live HTTP service can fail because the network or remote server is unavailable. Go’s standard-library `httptest` package provides local test infrastructure instead: a temporary server for testing an HTTP client, and a response recorder for testing a handler directly. section 6.5.4 section 8.2.1

ts := httptest.NewServer(
    http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "...")
}))
defer ts.Close()  #1

Create a server with `httptest.NewServer`, give it an `http.HandlerFunc` that writes a predictable response, pass `ts.URL` to the client under test, and close the server when the test ends. The client therefore needs a configurable URL rather than an exclusively hardcoded one. section 6.5.4

The same server handler can write an HTTP error status with `w.WriteHeader` to exercise a client’s failure path. This tests response handling without depending on the real exchange-rate endpoint. section 6.5.4

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
}

For a handler, build a request with `http.NewRequest`, pass an `httptest.NewRecorder()` to the handler, then inspect the recorded status code, headers, and body. Here the checks cover a created response and its JSON content. section 8.2.1

A recorder also works for a handler that produces HTML: check the recorded status, then compare the body with a fixture in `testdata`. Exact string equality is simple but brittle—an irrelevant whitespace change can fail the test. section 11.1.1

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Works through temporary-server setup and direct handler assertions, but does not develop a comprehensive HTML comparison strategy.
Examples
Tests an exchange-rate client against a temporary server, a game-creation handler with a recorder, and an HTML index against a fixture.
What it assumes
Assumes familiarity with Go tests and HTTP requests while showing how to create a test server and response recorder.
What you can do after
Apply it via httptest.NewServer and httptest.NewRecorder to test HTTP clients and handlers without relying on production endpoints.
How it connects
Connects HTTP handlers, configurable client URLs, response recorders, HTTP status codes, JSON assertions, and golden files.

Also explained in

Compare how 4 books explain httptest →

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.