You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 06:18:03