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

查看:97
本文介绍了如何模拟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 但只有Get and Post的模拟功能

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天全站免登陆