Go单元测试中如何校验发往外部API的请求是否设置了指定header
方法1:在自定义Responder中实时校验Header
你可以替换内置的httpmock.NewStringResponder,改用自定义响应函数,在返回Mock响应前直接校验收到的请求Header,将校验结果存在外部变量中后续断言即可:
var hasValidContentType bool httpmock.RegisterResponder(http.MethodPost, "do-not-exist.com", func(req *http.Request) (*http.Response, error) { // 直接校验请求Header hasValidContentType = req.Header.Get("Content-Type") == "application/json" // 返回预设的Mock响应 return httpmock.NewStringResponse(http.StatusOK, `{"data":{"Random": "Stuff"}}`), nil }, ) // 执行业务代码发起请求后,直接断言hasValidContentType的值即可
方法2:业务逻辑执行完成后批量校验请求
httpmock提供了获取所有已触发请求的接口,你可以在请求发送完成后,拉取所有匹配的请求统一校验Header:
// 先注册你原本的Responder httpmock.RegisterResponder(http.MethodPost, "do-not-exist.com", httpmock.NewStringResponder(http.StatusOK, `{"data":{"Random": "Stuff"}}`), ) // 执行业务代码发起请求... // 拉取所有匹配目标接口的POST请求 requests := httpmock.GetRequestsByMatcher(httpmock.MethodAndPathMatcher(http.MethodPost, "do-not-exist.com")) for _, req := range requests { if req.Header.Get("Content-Type") != "application/json" { t.Errorf("Content-Type异常,实际值为:%s", req.Header.Get("Content-Type")) } }
如果是给自定义http.Client绑定的非全局Mock,替换为对应Mock实例的GetAllRequests()方法拉取请求即可。
内容的提问来源于stack exchange,提问作者unitSphere
相关产品推荐
相关产品推荐

