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.

Go’s standard-library httptest package supplies test infrastructure for HTTP clients and handlers. A local test server gives a client a predictable response without relying on a remote service; a response recorder captures a handler’s output for inspection. section 6.5.4 section 8.2.1

For a client test, create a server with httptest.NewServer and an http.HandlerFunc that writes the desired response. Pass the server’s URL to the client and defer Close. Making the client URL configurable removes the hardcoded remote dependency and lets the test exercise the HTTP call locally. section 6.5.4

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

A small test server writes a fixed response and is closed when the test finishes. section 6.5.4

To test a handler directly, create a request with http.NewRequest and a recorder with httptest.NewRecorder. Call the handler with both, then check the recorded status, headers, and body. This keeps the test focused on the handler without starting a server. section 8.2.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 game-creation test checks the status, content type, and JSON response using a recorder and testify assertions. section 8.2.1

Checking HTML output

An index-handler test checks for HTTP 200 and compares the recorded body with a golden file in testdata. Exact string comparison is simple but brittle: tabs, carriage returns, or other harmless output changes can fail the test. section 11.1.1

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Demonstrates server setup and cleanup, configurable client URLs, and response recording through worked tests.
Examples
Tests an exchange-rate client against a local server, a game-creation handler’s JSON response, and an HTML index against a golden file.
What you can do after
Apply it via httptest to test HTTP clients and inspect handler responses.
How it connects
Connects HTTP handlers and dependency injection with unit testing, response 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.