【问题标题】:Go Test Coverage - Go Tool Not Recognize err != nil returnsGo Test Coverage - Go Tool Not Recognize err != nil 返回
【发布时间】:2022-01-07 13:12:08
【问题描述】:

我正在学习一些有关 Golang 测试覆盖率的知识,并且遇到了一些有趣的问题。

我有一个调用 API 和执行 http.Client.Do(request) 的基本代码。执行后,我检查错误并在找到时返回。

resp, err := Client.Do(request)

if err != nil {
    return response, err
}

另外,我已经为它添加了测试。我在哪里模拟 Do 函数并返回错误。

mocks.DoFunc = func(*http.Request) (*http.Response, error) {
    return nil, errors.New("hello world")
}

当我记录if err != nil 条件时,我可以看到我的代码正在运行并被这个简单的评估捕获。

我的问题在执行go tool cover -html=coverage.out 时开始。输出表明这个条件没有被覆盖。

所以,为什么我可以在 logging 和 go 工具没有检测到它时检查它,我错过了什么?

【问题讨论】:

    标签: unit-testing go testing


    【解决方案1】:

    好的。不确定,但有效。

    似乎测试顺序在 TestCoverage 上非常重要,创建从最少到第一个评估的测试if err != nil 成功了。

    我的代码做了一个简单的获取 API:

    1. 创建响应对象
    2. 格式化 URL + ID
    3. 创建一个 Http.NewREquest
    4. 评估 NewRequest 错误
    5. 执行 http.Client.Do(request)
    6. 评估错误
    7. 等等等等……

    ...

    response := &Response{}
    
    url := fmt.Sprintf(pokeapiURLById, pokeId)
    
    request, err := http.NewRequest(http.MethodGet, url, nil)
    
    if err != nil {
        return nil, err
    }
    
    resp, err := Client.Do(request)
    
    if err != nil {
        return nil, err
    }
    

    ...

    测试按以下顺序创建。

    func TestFetchById_WhenHttpNewRequestFails(t *testing.T) {...
    
    func TestFetchById_WhenClientDoFails(t *testing.T) {...
    

    首先,我测试 NewRequest 错误,然后测试 Client.Do(req) 错误。这样我就获得了 80% 的测试覆盖率....

    当我更改测试方法的顺序时:

    func TestFetchById_WhenClientDoFails(t *testing.T) {...
    
    func TestFetchById_WhenHttpNewRequestFails(t *testing.T) {...
    

    我有 100% 的测试覆盖率。 我不知道这是一个问题还是应该是这样的......但是,现在,它运行良好。

    【讨论】:

      猜你喜欢
      • 2019-09-16
      • 2018-11-14
      • 2020-07-29
      • 2022-12-21
      • 1970-01-01
      • 2020-07-25
      • 2019-02-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多