liveBook · Manning

Testify

As explained in Learn Go with Pocket-Sized Projects

testify is a Go testing library that provides assertions, requirements, and related test utilities.

testify is a Go testing library used here to check an HTTP handler’s response. Add it with `go get github.com/stretchr/testify`; its `assert` and `require` packages provide similar checks but handle failures differently. section 8.2.1

Choose the check based on whether the test can usefully continue:

  • Use `require` when a failure makes later checks pointless: `require.NoError(t, err)` stops the test if request creation fails. section 8.2.1
  • Use `assert` for checks that can run independently: compare the status, content type, and JSON response even if one comparison fails. 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 handler test creates a POST request and response recorder, calls the handler, then checks the recorded response. section 8.2.1

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains installation and the failure behavior of assert and require, then applies both; does not explore their internals.
Examples
Tests a POST handler with `require.NoError`, `assert.Equal`, and `assert.JSONEq`.
What it assumes
Assumes familiarity with Go tests and HTTP handlers while showing request and recorder setup.
What you can do after
Apply it via testify to stop on setup errors and check multiple response properties.
How it connects
Connects assertions and requirements to HTTP handler testing, `http.NewRequest`, and `httptest.NewRecorder`.

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.