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

如何在单元测试中模拟返回带timeout:true的deadlineExceededError

解决Mock HTTP客户端返回带Timeout标识的超时错误问题

要让Mock的HTTP客户端返回包含timeout: true特性的超时错误,核心是构造一个**实现了Timeout() bool方法并返回true**的错误类型,再嵌套到*url.Error中,模拟真实场景的错误结构。

实现步骤

  1. 定义自定义超时错误类型,实现error接口和Timeout() bool方法:
type timeoutError struct {
    wrappedErr error
}

func (e *timeoutError) Error() string {
    // 模拟真实超时的错误信息,也可直接复用wrappedErr的内容
    return "context deadline exceeded (Client.Timeout exceeded while awaiting headers)"
}

func (e *timeoutError) Timeout() bool {
    return true
}
  1. 修改Mock的Do函数,使用自定义错误构造完整的超时错误:
GetDoFunc = func(req *http.Request) (*http.Response, error) {
    return nil, &url.Error{
        Op:  "Post",
        URL: req.URL.String(), // 补充URL字段,更贴近真实请求场景
        Err: &timeoutError{wrappedErr: context.DeadlineExceeded},
    }
}

原理说明

真实HTTP超时返回的*net/http.httpError是未导出类型,但它实现了Timeout() bool方法并返回true。业务代码中判断超时通常通过该方法而非直接类型断言(比如用errors.As匹配interface{ Timeout() bool })。

自定义的timeoutError实现了相同的方法,因此在断言超时行为时,和真实场景的错误表现完全一致,能满足单元测试的断言需求。

单元测试断言示例

如果需要验证错误是否为超时错误,可以这样写:

err := yourFunctionUnderTest()
var timeoutErr interface{ Timeout() bool }
assert.True(t, errors.As(err, &timeoutErr) && timeoutErr.Timeout())

内容的提问来源于stack exchange,提问作者Tarta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 00:10:34