在为我的一个源文件 ( commonutil.go ) 创建单元测试时遇到问题
package util
import "github.com/nu7hatch/gouuid"
// GenerateUUID Returns generated UUID sequence
func GenerateUniqueID(hostname string) (string, error) {
var result, err = uuid.NewV4()
return hostname + ":" + result.String(), err
}
对于上面的源,我创建了测试文件“commonutil_test.go”(在同一个包中)
package util
import "testing"
func TestCommonUtil(t *testing.T) {
t.Run("Test generate UUID", func(t *testing.T) {
var uuid, _ = GenerateUniqueID ("test")
//fmt.Printf("UUID isa %v \n", uuid)
if uuid == "" {
t.Errorf("UUID expected, but result is empty ")
}
})
然而,当尝试执行“go test util/commonutil_test.go”时,它显示:
util\commonutil_test.go:8: undefined: GenerateUniqueID
FAIL command-line-arguments [build failed]
在测试中更改为 util.GenerateUniqueID 可以解决问题,但是当使用 Goconvey 运行覆盖时将导致构建失败:
can't load package: import cycle not allowed package rudygunawan.com/MyProject/HFLC-Go/util imports rudygunawan.com/MyProject/HFLC-Go/util
有解决这个问题的想法吗?我很困惑。
Go版本是go1.7.1 windows/386
最佳答案
当我尝试运行单个测试文件时,我遇到了类似的问题。
我想要这样,因为它是一种测试驱动的开发,我只想对我目前正在处理的代码运行测试,而不是所有 x 分钟的运行测试。
解决方案原来不是从文件运行测试,而是按名称(实际上是正则表达式)运行特定测试。所以在你的情况下我猜它会是:
go test ./util -run TestCommonUtil
另一种方法似乎是列出构建测试代码所需的所有文件:
go test util/commonutil_test.go util/commonutil.go
关于Golang 无法在同一个包中进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39737599/