liveBook · Manning

Testify/require

As explained in Learn Go with Pocket-Sized Projects

testify/require is a package providing fatal test assertions that stop the current test when a condition fails.

Use `testify/require` when a failed check makes the rest of a Go test pointless. A failed `require` check displays a message and stops that test; a failed `testify/assert` check displays a message but lets it continue. Add both through `go get github.com/stretchr/testify`. 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
}

`require.NoError(t, err)` guards request creation before the handler is called. The response checks use `assert.Equal` and `assert.JSONEq` so multiple results can be checked. section 8.2.1

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Defines failure behavior and demonstrates one assertion call without exploring implementation internals.
Examples
Shows require.NoError checking http.NewRequest before a POST /games handler test.
What you can do after
Apply it via testify/require to stop a test when a prerequisite check fails.
How it connects
Contrasts with testify/assert and accompanies HTTP handler testing with httptest.NewRecorder.

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.