【发布时间】:2017-08-13 08:17:02
【问题描述】:
在Go 编程语言的第 11.2.4 节中,有一个外部测试通过 fmt 的 export_test.go 中的 IsSpace 声明访问 fmt.isSpace() 的示例文件。这似乎是一个完美的解决方案,所以我就是这样做的:
a/a.go:
package a
var x int
func Set(v int) {
x = v
}
a/a_test.go:
package a
import "testing"
func TestSet(t *testing.T) {
Set(42)
if x != 42 {
t.Errorf("x == %d (expected 42)", x)
}
}
func Get() int {
return x
}
(在a/ 中运行go test 工作正常。)
b/b.go:
package b
import "path/to/a"
func CallSet() {
a.Set(105)
}
b/b_test.go
package b
import (
"testing"
"path/to/a"
)
func TestCallSet(t *testing.T) {
CallSet()
if r := a.Get(); r != 105 {
t.Errorf("Get() == %d (expected 105)", r)
}
}
不幸的是,当我在 b/ 中运行 go test 时,我得到:
./b_test.go:11: undefined: a.Get
尝试使用go test ./... 同时运行两组测试没有帮助。
经过相当多的探索后,我发现“The *_test.go files are compiled into the package only when running go test for that package”(强调我的)。 (所以,换句话说,我可以从a/ 中的a_test 外部测试包访问a.Get,但不能从a/ 之外的任何包访问。)
是否有其他方法可以允许来自一个包的测试访问另一个包的内部数据,以进行集成测试?
【问题讨论】:
-
如果反对这个问题的人能提出如何改进的建议,我将不胜感激。
-
您无法访问来自另一个包期间的未导出标识符。这是 Go 包的基本前提,所以这些测试示例没有什么不同。
-
为什么要在集成测试中关心包的内部结构?这是黑盒测试的完美示例。顾名思义,其预期目的是测试系统不同部分的集成,您可以通过它们的公共接口访问这些特定部分。
-
@cpcallen 我不是 100% 确定,所以不要引用我的话,但我认为链接器会删除未使用的符号,因此在一些特殊情况下它们不是,例如,如果您在
testing_*.go中声明的func仅在*_test.go文件中使用,那么我怀疑它不会进入最终的可执行文件......
标签: testing go integration-testing