了解测试范围

I have a simple package in my Go program to generate a hash ID.

I've also written a test for it but not able to understand why I'm only getting 83% of statements covered.

Below is my package function code:

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
}

Below is my test code:

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)
}

Running Go test with coverprofile mentions that following portions are not covered by the test:

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

Any advice?

Thanks for the replies.

I broken down my function GenHash() into smaller pieces to test the errors returned by the go-hashids package. Now I'm able to increase the test coverage percentage.

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)

}