liveBook · Manning

Testify/assert

As explained in Learn Go with Pocket-Sized Projects

testify/assert is a Go assertion library that reports failed test conditions without immediately stopping the test.

Use `testify/assert` when a Go test should check several results even if one check fails. A failed assertion reports a message and lets the test continue. By contrast, `testify/require` stops the test on failure; use it when continuing would not make sense. Add both through `go get github.com/stretchr/testify`. section 8.2.1

Check a game-creation response

Create a POST request with `http.NewRequest`, check its error with `require.NoError`, then pass an `httptest.NewRecorder` to the handler. Afterward, use `assert.Equal` for the 201 status and JSON content type, and `assert.JSONEq` for the response body. The assertions let the test report multiple response mismatches in one run. 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 shows where `require.NoError` guards setup and where three assertions check the recorded response. section 8.2.1

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Defines failure behavior and demonstrates assertion calls, but does not examine library internals.
Examples
Checks a game-creation handler’s status, content type, and JSON response body.
What it assumes
Assumes familiarity with Go tests and HTTP handlers while showing how to create a request and recorder.
What you can do after
Apply it via `testify/assert` to report several response mismatches in one Go test run.
How it connects
Contrasts with `testify/require` and works alongside `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.