【发布时间】: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你会看到的。