gpt4 book ai didi

go - 将函数拆分为 2 个函数以进行测试覆盖

转载 作者:IT王子 更新时间:2023-10-29 01:55:09 26 4
gpt4 key购买 nike

如何测试 ioutil.ReadAll(rep.Body) 的错误?我是否需要将我的函数一分为二,一个发出请求,另一个读取正文并返回字节和错误?

func fetchUrl(URL string) ([]bytes, error) {
resp, err := http.Get(URL)
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return nil, err
}
return body, nil
}

最佳答案

Do I need to split my function in two, one which will make the request, and another one which will read the body and return the bytes and error?

第一个叫做http.Get,另一个叫做ioutil.ReadAll,所以我认为没有什么可以拆分的。您刚刚创建了一个函数,该函数同时使用了另外两个函数,您应该假设它们工作正常。您甚至可以简化您的函数以使其更加明显:

func fetchURL(URL string) ([]byte, error) {
resp, err := http.Get(URL)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}

如果你想测试什么是你的 fetchURL 函数,同时使用 http.Getioutil.ReadAll。我个人不会费心去直接测试它,但如果你坚持这样做,你可以为单个测试覆盖 http.DefaultTransport 并提供你自己的,它返回 http.Response with body 实现了一些错误场景(例如,在 body 读取期间出错)。

这是草图的想法:

type BrokenTransport struct {
}

func (*BrokenTransport) RoundTrip(*http.Request) (*http.Response, error) {
// Return Response with Body implementing specific error behaviour
}

http.DefaultTransport = &BrokenTransport{}

// http.Get will now use your RoundTripper.
// You should probably restore http.DefaultTransport after the test.

关于go - 将函数拆分为 2 个函数以进行测试覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34510055/

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