Go单元测试中的包可见性

huangapple go评论85阅读模式
英文:

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

huangapple
  • 本文由 发表于 2013年8月27日 03:04:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/18451186.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定