英文:
Package visibility in Go Unit Tests
问题
给定以下Go代码文件(命名为server.go):
package glimpse
func SplitHeader() string {
return "hi there"
}
以及相应的测试文件(server_test.go):
package glimpse
import (
"testing"
)
func TestSplitHeader(t *testing.T) {
answer := SplitHeader()
if answer == "" {
t.Error("No return value")
}
}
为什么执行以下命令:
go test server_test.go
会返回以下错误信息:
# command-line-arguments
./server_test.go:9: undefined: SplitHeader
我肯定是漏掉了一些非常明显的东西。
英文:
Given the following code file (named server.go) in Go:
package glimpse
func SplitHeader() string {
return "hi there"
}
and the accompanying test file (server_test.go):
package glimpse
import (
"testing"
)
func TestSplitHeader(t *testing.T) {
answer := SplitHeader()
if answer == "" {
t.Error("No return value")
}
}
Why is it the following command:
go test server_test.go
returns
# command-line-arguments
./server_test.go:9: undefined: SplitHeader
I'm certainly missing something catastrophically obvious.
答案1
得分: 6
只使用以下命令来进行测试:
$ go test
在包目录中执行该命令。如果你将特定的文件作为 go test
的参数,那么只有这些文件会被考虑用于构建测试二进制文件。这就解释了出现“undefined”错误的原因。
作为替代方案,可以将“导入路径”作为 go test
的参数,例如:
$ go test foo.com/glimpse
英文:
Use only
$ go test
from within the package directory to perform testing. If you name specific files as an argument to go test
, then only those file will be considered for the build of the test binary. That explains the 'undefined' error.
As an alternative, use "import path" as an argument to go test
instead, for example
$ go test foo.com/glimpse
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论