gpt4 book ai didi

unit-testing - 如何模拟 http.Client Do 方法

转载 作者:行者123 更新时间:2023-12-01 22:41:17 26 4
gpt4 key购买 nike

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

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

我使用基本身份验证发出 http 获取请求
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
但只有获取和发布的模拟

也许我应该以不同的方式来做。
我会很感激你的建议

最佳答案

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

type ClientMock struct {
}

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

然后你可以注入(inject)这个 ClientMock结构到你的 GetOverview功能 Here是 Go Playground 中的一个示例。

关于unit-testing - 如何模拟 http.Client Do 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63664787/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com