在辅助函数中包装httptest方法

时间:2018-09-04 08:00:04

标签: unit-testing http go gomega

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

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)

}

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

1 个答案:

答案 0 :(得分: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

}
相关问题