相关疑难解决方法(0)

Go中的模拟函数

我正在通过编写一个小型的个人项目来学习Go.虽然它很小,但我决定从一开始就进行严格的单元测试,以便在Go上学习好习惯.

琐碎的单元测试都很好,花花公子,但我现在对依赖感到困惑; 我希望能够用模拟函数替换一些函数调用.这是我的代码片段:

func get_page(url string) string {
    get_dl_slot(url)
    defer free_dl_slot(url)

    resp, err := http.Get(url)
    if err != nil { return "" }
    defer resp.Body.Close()

    contents, err := ioutil.ReadAll(resp.Body)
    if err != nil { return "" }
    return string(contents)
}

func downloader() {
    dl_slots = make(chan bool, DL_SLOT_AMOUNT) // Init the download slot semaphore
    content := get_page(BASE_URL)
    links_regexp := regexp.MustCompile(LIST_LINK_REGEXP)
    matches := links_regexp.FindAllStringSubmatch(content, -1)
    for _, match := range matches{
        go serie_dl(match[1], match[2])
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望能够测试downloader()而不实际通过http获取页面 - 即通过模拟get_page(更容易,因为它只返回页面内容作为字符串)或http.Get().

我找到了这个帖子:https …

unit-testing mocking go

129
推荐指数
4
解决办法
8万
查看次数

标签 统计

go ×1

mocking ×1

unit-testing ×1