Go 了解测试覆盖率
我的Go程序中有一个简单的包来生成哈希ID 我也为它写了一个测试,但无法理解为什么我只得到了83%的陈述 以下是我的软件包功能代码:Go 了解测试覆盖率,go,testify,Go,Testify,我的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
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
}
有什么建议吗?谢谢你的回复 我将我的函数GenHash()分解成更小的部分,以测试go hashids包返回的错误。现在我可以提高测试覆盖率了
您是否使用导致hashids.NewWithData(hd)返回错误的输入进行测试?如果没有,那么将永远不会执行
If
的主体,因此您的测试不会覆盖它。我建议使用一个编辑器来实时显示哪些行被覆盖。原子能做到这一点。我希望VS Code、Goland或任何其他流行的编辑器/IDE也能做到这一点。go-test-coverprofile=coverage.out&&go-tool-cover-html=coverage.out
。
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)
}