登录
首页 >  Golang >  Go问答

创建单元测试时超时的deadlineExceededError标志

来源:stackoverflow

时间:2024-03-09 22:09:31 136浏览 收藏

大家好,今天本人给大家带来文章《创建单元测试时超时的deadlineExceededError标志》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

问题内容

我正在尝试在我的项目中创建一个单元测试,在其中模拟 http 客户端并设置客户端必须返回的响应。 我需要这样的行为,因为我的代码需要做出相应的行为,以防 http 客户端因超时而失败:因此我需要模拟 http 客户端以返回一个 deadlineexceedederror 并从中进行单元测试。

到目前为止,我尝试的是以 client.do 返回的方式模拟客户端 do 函数:

getdofunc = func(*http.request) (*http.response, error) {
    return nil, &url.error{
        op:  "post",
        err: context.deadlineexceeded,
    }
}

它可以工作,但不完全,这意味着当我以这种模拟行为执行代码时,返回的错误类型是:

error(*net/url.error) *{op: "post", url: "", err: error(context.deadlineexceedederror) {}}

这又是正确的,但不完全。为什么?因为如果我运行代码并且发生真正的超时,我会得到更完整的东西:

error(*net/url.Error) *{Op: "Post", URL: "http://localhost:4500/scan/", Err: error(*net/http.httpError) *{err: "context deadline exceeded (Client.Timeout exceeded while awaiting headers)", timeout: true}}

最让我感兴趣的是timeout: true。如果我设法告诉我的模拟返回它,我可以断言这一点,我发现这比仅断言返回的错误是 deadlineexceedederror 类型更完整。


正确答案


为了避免测试过于复杂,我建议您采用这种方法。首先,首先定义您的错误:

type timeouterror struct {
    err     string
    timeout bool
}

func (e *timeouterror) error() string {
    return e.err
}

func (e *timeouterror) timeout() bool {
    return e.timeout
}

这样,timeouterror就同时实现了error()timeout接口。
然后您必须为 http 客户端定义模拟:

type mockclient struct{}

func (m *mockclient) do(req *http.request) (*http.response, error) {
    return nil, &timeouterror{
        err:     "context deadline exceeded (client.timeout exceeded while awaiting headers)",
        timeout: true,
    }
}

这只是返回上面定义的错误和 nil 作为 http.response。最后,让我们看看如何编写示例单元测试:

func TestSlowServer(t *testing.T) {
    r := httptest.NewRequest(http.MethodGet, "http://example.com", nil)
    client := &mockClient{}

    _, err := client.Do(r)

    fmt.Println(err.Error())
}

如果您调试此测试并在 err 变量上使用调试器暂停,您将看到想要的结果。
通过这种方法,您可以实现所需的功能,而无需带来任何额外的复杂性。让我知道是否适合您!

今天关于《创建单元测试时超时的deadlineExceededError标志》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>