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

标签 unit-testing testing go mocking

我正在尝试找到一种解决方案来编写测试和模拟 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/

相关文章:

c# - Xamarin UI 测试 : Is it possible to interact with the OS level dialogues during UITesting

go - 从某个 channel 接收到无处可去的地方

android - Espresso 自定义 ViewMatcher 不匹配描述未出现在日志中

c++ - BOOST_CHECK 无法为自定义类型编译 operator<<

python - python 项目的 sonarqube 没有显示任何测试覆盖率

r - 如何在 R 中使用 testthat 处理 "example files"?

java - ActivityInstrumentationTestCase2 问题 - 由于我正在为其编写测试的代码中的 invalidate() 调用导致测试挂起

go - 防止第三方导入包

go - 如何在 Go 中反转数组?

asp.net-mvc - 如何以正确的方式对 ASP.NET MVC 2.0 Controller 进行单元测试!