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

标签 go

如何测试 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/

相关文章:

string - 在循环中更新字符串值

正则表达式排除不适用于 inotifywait 的非 golang 文件

c# - 谷歌从 golang 到 c# 的 protobuf - 协议(protocol)消息包含无效标签(零)

go - 如果条件为假,如何停止 golang 中的 cron 作业?

go - 一个 ticker 是否通过它的 ticker.C 告诉一个 goroutine 它被停止了?

pointers - Go 的指针何时取消引用自身

for-loop - 转到如何正确使用 for ... range 循环

go - 为什么这个程序在 liteIde 中工作,但在从终端运行时因无效指针引用而崩溃?

unit-testing - 为从中读取的函数填充 os.Stdin

go - 如何对数组中的所有数字进行平方?戈朗