了解测试范围

时间:2019-02-07 08:21:23

标签: 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 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
    }

有什么建议吗?

1 个答案:

答案 0 :(得分:-2)

感谢您的答复。

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

enter image description here

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)

}