Wrapping httptest methods in a helper function

82 Views Asked by At

In my handler tests, I use the pattern of serving a test request with an authentication token in the header a large number of times. To abstract this, and save myself a large number of lines, I've written the following function:

func serveTestReq(payload string, route string, method string, handlerfunc func(w http.ResponseWriter, r *http.Request), token string) {
        body := strings.NewReader(payload)
        req, err := http.NewRequest(method, route, body)
        Expect(err).NotTo(HaveOccurred())

        req.Header.Add("Content", "application/json")
        req.Header.Add("Authorization", "Bearer "+token)

        handler := authMiddleware(handlerfunc)
        rr := httptest.NewRecorder()
        handler.ServeHTTP(rr, req)

}

However if I call this function twice (to test for idempotent POSTs, for example) the request seems to only be served once. Is there something wrong with the above function?

1

There are 1 best solutions below

0
On

The problem was that I wasn't checking for the HTTP Response generated in the function. The correct function looks like:

func serveTestReq(payload string, route string, method string, handlerfunc func(w http.ResponseWriter, r *http.Request), token string) *httptest.RepsonseRecorder {
        body := strings.NewReader(payload)
        req, err := http.NewRequest(method, route, body)
        Expect(err).NotTo(HaveOccurred())

        req.Header.Add("Content", "application/json")
        req.Header.Add("Authorization", "Bearer "+token)

        handler := authMiddleware(handlerfunc)
        rr := httptest.NewRecorder()
        handler.ServeHTTP(rr, req)

        return rr

}