在辅助函数中包装httptest方法

问题描述 投票:0回答:1

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

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)

}

但是,如果我将此函数调用两次(例如,测试幂等POSTs),请求似乎只提供一次。上述功能有问题吗?

unit-testing http go gomega
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

}
© www.soinside.com 2019 - 2024. All rights reserved.