尝试运行“go test sum_test.go”会返回错误:
./sum_test.go:18:13: undefined: SumInt8 FAIL 命令行参数 [构建失败]
我正在学习 golang 的入门课程。我们的老师分发了一个代码文件 sum.go 和一个测试文件 sum_test.go。尝试在 sum_test.go 上运行“go test”会返回上面的错误。代码在我们的老师 mac 上运行良好,他在重现问题时遇到了困难。这是我的 go 环境设置:https : //pastebin.com/HcuNVcAF
sum.go
package sum
func SumInt8(a, b int8) int8 {
return a + b
}
func SumFloat64(a, b float64) float64 {
return a + b
}
Run Code Online (Sandbox Code Playgroud)
sum_test.go
package sum
import "testing"
// Check https://golang.org/ref/spec#Numeric_types and stress the limits!
var sum_tests_int8 = []struct{
n1 int8
n2 int8
expected int8
}{
{1, 2, 3},
{4, 5, 9},
{120, 1, 121},
}
func TestSumInt8(t *testing.T) {
for _, v := range sum_tests_int8 {
if val := SumInt8(v.n1, v.n2); val != v.expected {
t.Errorf("Sum(%d, %d) returned %d, expected %d",
v.n1, v.n2, val, v.expected)
}
}
}
Run Code Online (Sandbox Code Playgroud)
我没有看到特别的错误,所以我希望“go test sum_test.go”运行并成功。但是它似乎在 sum.go 中找不到方法 SumInt8。
pet*_*rSO 18
Run Code Online (Sandbox Code Playgroud)$ go help packages
许多命令适用于一组包:
Run Code Online (Sandbox Code Playgroud)go action [packages]
通常,[packages] 是导入路径的列表。
作为根路径或以 . 或 .. 元素被解释为文件系统路径并表示该目录中的包。
否则,导入路径 P 表示在目录 DIR/src/P 中为 GOPATH 环境变量中列出的某些 DIR 找到的包(有关更多详细信息,请参阅:'go help gopath')。
如果未给出导入路径,则该操作适用于当前目录中的包。
作为一种特殊情况,如果包列表是来自单个目录的 .go 文件列表,则该命令将应用于由这些文件组成的单个合成包,忽略这些文件中的任何构建约束并忽略其中的任何其他文件目录。
列出当前目录下测试使用的所有文件:
go test sum_test.go sum.go
Run Code Online (Sandbox Code Playgroud)
或者简单地测试当前目录中的完整包。
go test
Run Code Online (Sandbox Code Playgroud)
例如,
$ go test -v sum_test.go sum.go
=== RUN TestSumInt8
--- PASS: TestSumInt8 (0.00s)
PASS
ok command-line-arguments 0.002s
$
Run Code Online (Sandbox Code Playgroud)
或者,对于完整的包
$ go test -v
=== RUN TestSumInt8
--- PASS: TestSumInt8 (0.00s)
PASS
ok so/sum 0.002s
$
Run Code Online (Sandbox Code Playgroud)
选项“-v”产生详细输出。
sum_test.go
:
package sum
import "testing"
// Check https://golang.org/ref/spec#Numeric_types and stress the limits!
var sum_tests_int8 = []struct {
n1 int8
n2 int8
expected int8
}{
{1, 2, 3},
{4, 5, 9},
{120, 1, 121},
}
func TestSumInt8(t *testing.T) {
for _, v := range sum_tests_int8 {
if val := SumInt8(v.n1, v.n2); val != v.expected {
t.Errorf("Sum(%d, %d) returned %d, expected %d",
v.n1, v.n2, val, v.expected)
}
}
}
Run Code Online (Sandbox Code Playgroud)
sum.go
:
package sum
func SumInt8(a, b int8) int8 {
return a + b
}
func SumFloat64(a, b float64) float64 {
return a + b
}
Run Code Online (Sandbox Code Playgroud)