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
