func TestMyHandler(t *testing.T) { req, err := http.NewRequest("GET", "/myendpoint", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() handler := http.HandlerFunc(MyHandler) handler.ServeHTTP(rr, req) assert.Equal(t, http.StatusOK, rr.Code) assert.Contains(t, rr.Body.String(), "expected response") }
func TestMyHandler(t *testing.T) { req, err := http.NewRequest("POST", "/myendpoint", bytes.NewBufferString(`{"foo":"bar"}`)) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() handler := http.HandlerFunc(MyHandler) handler.ServeHTTP(rr, req) assert.Equal(t, http.StatusCreated, rr.Code) assert.Equal(t, "application/json", rr.Header().Get("Content-Type")) }In this example, we are testing the same MyHandler function, but this time with a POST request to the same endpoint with a JSON body. We use the bytes.NewBufferString function to create a new buffer from the stringified JSON data. We use the same pattern as the previous example to record the HTTP response and perform some assertions on the response, this time checking that the response status is 'Created', and that the response headers include the "Content-Type: application/json" header.