0

在我的处理程序测试中,我多次使用在标头中提供带有身份验证令牌的测试请求的模式。为了抽象这一点,并为自己节省大量行数,我编写了以下函数:

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)

}

但是,如果我两次调用此函数(例如,为了测试 idempotent POST),请求似乎只被服务一次。上面的功能有问题吗?

4

1 回答 1

0

问题是我没有检查函数中生成的 HTTP 响应。正确的函数如下所示:

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

}
于 2018-09-04T08:44:40.240 回答