如何模拟 http.Client Do 方法 [英] How to mock http.Client Do method

查看:24
本文介绍了如何模拟 http.Client Do 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试寻找一种解决方案来编写测试和模拟 HTTP 响应.在我接受接口的函数中:

I'm trying to find a solution to write test and mock HTTP response. In my function where I accept interface:

type HttpClient interface {
    Do(req *http.Request) (*http.Response, error)
}

我使用基本身份验证发出 http 获取请求

I makes http get request with base auth

func GetOverview(client HttpClient, overview *Overview) (*Overview, error) {

    request, err := http.NewRequest("GET", fmt.Sprintf("%s:%s/api/overview", overview.Config.Url, overview.Config.Port), nil)
    if (err != nil) {
        log.Println(err)
    }
    request.SetBasicAuth(overview.Config.User, overview.Config.Password)
    resp, err := client.Do(request)

如何模拟这个 HttpClient?我正在寻找模拟库,例如:https://github.com/h2non/gock但只有获取和发布的模拟

How can I mock this HttpClient? I'm looking for mock library, for instance: https://github.com/h2non/gock but there is only mock for Get and Post

也许我应该换一种方式.我会很感激你的建议

Maybe I should do it in a different way. I'll be grateful for advice

推荐答案

任何具有与您在接口中的签名匹配的方法的结构都将实现该接口.例如,您可以创建一个结构 ClientMock

Any struct with a method matching the signature you have in your interface will implement the interface. For example, you could create a struct ClientMock

type ClientMock struct {
}

用方法

func (c *ClientMock) Do(req *http.Request) (*http.Response, error) {
    return &http.Response{}, nil
}

然后您可以将此 ClientMock 结构体注入到您的 GetOverview 函数中.这里是 Go Playground 中的一个示例.

You could then inject this ClientMock struct into your GetOverview func. Here's an example in the Go Playground.

这篇关于如何模拟 http.Client Do 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆