登录
首页 >  Golang >  Go问答

哪种方法是最常用的在 Go 中进行 HTTP 请求测试功能?

来源:stackoverflow

时间:2024-03-20 19:09:40 400浏览 收藏

在 Go 中进行 HTTP 请求测试功能时,最常用的方法是使用模拟框架,例如 Testify。通过创建模拟 HTTP 客户端,可以避免在测试期间进行实际 HTTP 调用,从而节省时间和资源。这有助于隔离被测代码并确保测试结果不受外部因素的影响,例如网络中断。此外,模拟 HTTP 客户端还允许测试人员控制请求和响应行为,从而创建各种测试场景并验证代码的鲁棒性。

问题内容

我有一个有趣的小天气应用程序。只需 99 美元/天,该应用程序就会每天检查天气,如果西雅图下雨,就给圣地亚哥人民送把雨伞。

我将这两个函数用作我的应用程序的一部分:

func IsRaining() (bool, error) {
    resp, err := http.Get("https://isitraining.in/Seattle")
    if err != nil {
        return false, fmt.Errorf("could not fetch raining status: %w", err)
    }

    parsed, err := weather.Parse(resp)
    if err != nil {
        return false, fmt.Errorf("could not parse the weather: %w", err)
    }

    return parsed.IsRaining, nil
}

func SendUmbrella() error {
    postData := umbrellaPostData()
    resp, err := http.Post("https://amazon.com", "text/html", &postData)
    if err != nil {
        return fmt.Errorf("could not send umbrella: %w", err)
    }
    return nil
}

我想测试 israining()sendumbrella(),但我不想每次运行测试时都给某人送一把雨伞;我的工程师使用 tdd,而且我确实有预算,你知道。与 israining() 相同,如果互联网中断怎么办?无论风雨无阻,我仍然需要能够通过测试运行。

我希望以一种使代码保持符合人体工程学和可读性的方式来执行此操作,但我绝对需要能够测试那些依赖于 http 的函数。在 go 中执行此操作最惯用的方法是什么?

附注我正在使用作证。在评论中告诉我我是如何对惯用的 go 失去任何希望的:)


正确答案


我不知道什么是“最惯用的”,但与任何其他语言一样,硬编码的 classes 包是令人头痛的。不要直接调用 http 包上的方法,而是创建一个 httpclient 接口。然后模拟httpclient接口。

您可以将 httpclient 传递到函数中,但将它们转换为结构上的方法更有意义。

// set up an interface for your http client, same as http.client.
type httpclient interface {
    get(string) (*http.response, error)
}

// make a struct to hang the client and methods off of.
type umbrellagiver struct {
    client httpclient
}

// a cut down example method.
func (giver umbrellagiver) getexample() ([]byte, error) {
    resp, err := giver.client.get("https://example.com")
    if err != nil {
        return nil, err
    }
    defer resp.body.close()
    return io.readall(resp.body)
}

然后可以将一个模拟的 httpclient 放入您的伞形给予者中。

// Our mocked client.
type mockedClient struct {
    mock.Mock
}

// Define the basic mocked Get method to record its arguments and
// return its mocked values.
func (m mockedClient) Get(url string) (*http.Response, error) {
    args := m.Called(url)
    if args.Get(0) == nil {
        return nil, args.Error(1)
    } else {
        return args.Get(0).(*http.Response), args.Error(1)
    }
}

func main() {
    // Make a mockedClient and set up an expectation.
    client := new(mockedClient)

    // Make an umbrellaGiver which uses the mocked client.
    s := umbrellaGiver { client: client }

    // Let's test what happens when the call fails.
    client.On(
        "Get", "https://example.com",
    ).Return(
        nil, errors.New("The system is down"),
    )

    body, err := s.getExample()
    if err != nil {
        panic(err)
    }
    fmt.Printf("%s", body)
}

查看Mocking HTTP Requests in Golang

好了,本文到此结束,带大家了解了《哪种方法是最常用的在 Go 中进行 HTTP 请求测试功能?》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

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