猿问

Go test <function> 返回 undefined: <function>

尝试运行“go test sum_test.go”返回错误:

./sum_test.go:18:13: undefined: SumInt8 FAIL command-line-arguments [build failed]

我正在学习 golang 的入门课程。我们的老师分发了一个代码文件 sum.go 和一个测试文件 sum_test.go。尝试在 sum_test.go 上运行“go test”会返回上述错误。代码在我们老师的 mac 上运行良好,但他在重现问题时遇到了困难。这是我的环境设置:https://pastebin.com/HcuNVcAF

求和.go

package sum


func SumInt8(a, b int8) int8 {

  return a + b

}


func SumFloat64(a, b float64) float64 {

  return a + b

}

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)

    }

  }

}

我没有看到特别的错误,所以我希望“go test sum_test.go”能够运行并成功。但是它似乎无法在 sum.go 中找到 SumInt8 方法。


茅侃侃
浏览 209回答 1
1回答

慕妹3146593

$&nbsp;go&nbsp;help&nbsp;packages许多命令适用于一组包:go&nbsp;action&nbsp;[packages]通常,[packages] 是一个导入路径列表。导入路径是根路径或以 .&nbsp;或 .. 元素被解释为文件系统路径并表示该目录中的包。否则,导入路径 P 表示在目录 DIR/src/P 中找到的包,用于 GOPATH 环境变量中列出的某些 DIR(有关更多详细信息,请参见:'go help gopath')。如果没有给出导入路径,则该操作适用于当前目录中的包。作为一种特殊情况,如果包列表是来自单个目录的 .go 文件列表,则该命令将应用于由这些文件组成的单个综合包,忽略这些文件中的任何构建约束并忽略中的任何其他文件目录。列出测试中使用的当前目录下的所有文件:go&nbsp;test&nbsp;sum_test.go&nbsp;sum.go或者简单地测试当前目录中的完整包。go&nbsp;test例如,$ go test -v sum_test.go sum.go=== RUN&nbsp; &nbsp;TestSumInt8--- PASS: TestSumInt8 (0.00s)PASSok&nbsp; &nbsp; &nbsp; command-line-arguments&nbsp; 0.002s$&nbsp;或者,对于完整的包$ go test -v=== RUN&nbsp; &nbsp;TestSumInt8--- PASS: TestSumInt8 (0.00s)PASSok&nbsp; &nbsp; &nbsp; so/sum&nbsp; 0.002s$选项“-v”产生详细的输出。sum_test.go:package sumimport "testing"// Check https://golang.org/ref/spec#Numeric_types and stress the limits!var sum_tests_int8 = []struct {&nbsp; &nbsp; n1&nbsp; &nbsp; &nbsp; &nbsp;int8&nbsp; &nbsp; n2&nbsp; &nbsp; &nbsp; &nbsp;int8&nbsp; &nbsp; expected int8}{&nbsp; &nbsp; {1, 2, 3},&nbsp; &nbsp; {4, 5, 9},&nbsp; &nbsp; {120, 1, 121},}func TestSumInt8(t *testing.T) {&nbsp; &nbsp; for _, v := range sum_tests_int8 {&nbsp; &nbsp; &nbsp; &nbsp; if val := SumInt8(v.n1, v.n2); val != v.expected {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; t.Errorf("Sum(%d, %d) returned %d, expected %d",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; v.n1, v.n2, val, v.expected)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}sum.go:package sumfunc SumInt8(a, b int8) int8 {&nbsp; &nbsp; return a + b}func SumFloat64(a, b float64) float64 {&nbsp; &nbsp; return a + b}
随时随地看视频慕课网APP

相关分类

Go
我要回答