【问题标题】:Understanding Test Coverage了解测试覆盖率
【发布时间】:2019-02-07 08:21:22
【问题描述】:

我的 Go 程序中有一个简单的包来生成哈希 ID。

我还为它编写了一个测试,但无法理解为什么我只覆盖了 83% 的语句。

下面是我的包函数代码:

package hashgen

import (
    "math/rand"
    "time"

    "github.com/speps/go-hashids"
)

// GenHash function will generate a unique Hash using the current time in Unix epoch format as the seed
func GenHash() (string, error) {

    UnixTime := time.Now().UnixNano()
    IntUnixTime := int(UnixTime)

    hd := hashids.NewData()
    hd.Salt = "test"
    hd.MinLength = 30
    h, err := hashids.NewWithData(hd)
    if err != nil {
        return "", err
    }
    e, err := h.Encode([]int{IntUnixTime, IntUnixTime + rand.Intn(1000)})

    if err != nil {
        return "", err
    }

    return e, nil
}

下面是我的测试代码:

package hashgen

import (
    "testing"

    "github.com/stretchr/testify/assert"
)

func TestGenHash(t *testing.T) {
    hash, err := GenHash()
    if err != nil {
        assert.Error(t, err, "Not able to generate Hash")

    }
    assert.Nil(t, err)
    assert.True(t, len(hash) > 0)
}

使用coverprofile 运行Go 测试提到测试未涵盖以下部分:

if err != nil {
        return "", err
    }

有什么建议吗?

【问题讨论】:

  • 您是否使用导致hashids.NewWithData(hd) 返回错误的输入进行测试?如果没有,那么if 的主体将永远不会被执行,所以你的测试不会覆盖它。
  • 我建议使用能够实时显示哪些行被覆盖的编辑器。原子做到这一点。我希望 VS Code、Goland 或任何其他流行的编辑器/IDE 也能做到这一点。
  • go test -coverprofile=coverage.out && go tool cover -html=coverage.out 你会看到的。

标签: go testify


【解决方案1】:

感谢您的回复。

我将函数 GenHash() 分解为更小的部分,以测试 go-hashids 包返回的错误。现在我可以提高测试覆盖率。

package hashgen

import (
    "testing"

    "github.com/stretchr/testify/assert"
)

func TestGenHash(t *testing.T) {
    hash, err := GenHash()
    if err != nil {
        assert.Error(t, err, "Not able to generate Hash")

    }
    assert.Nil(t, err)
    assert.True(t, len(hash) > 0)
}

func TestNewhdData(t *testing.T) {
    hd := newhdData()

    assert.NotNil(t, hd)
}

func TestNewHashID(t *testing.T) {
    hd := newhdData()

    hd.Alphabet = "A "
    hd.Salt = "test"
    hd.MinLength = 30

    _, err := newHashID(hd)

    assert.Errorf(t, err, "HashIDData does not meet requirements: %v", err)

}

【讨论】:

    猜你喜欢
    • 2020-09-22
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多