go test遇到的同一包下的变量报错undefined

134 阅读1分钟

使用go test array_test.go命令执行测试文件时,报错显示调用的同一包下array.go文件中的方法undefined。

原因是go test会为指定的源码文件生成一个虚拟代码包——“command-line-arguments”,而array_test.go引用了其他包中的数据并不属于代码包“command-line-arguments”,编译不通过,错误自然发生了。

因此,我们可以在go test的时候加上引用的包。

# 单个文件测试
go test -v my_test.go my_funcs.go

# 单个文件测试
go test -v my_test.go my_funcs.go -test.Run TestIntArray

# 若依赖过多, 可在目录下运行go test 测试所有
go test