英文:
How to export data from a test package and use them in another test package in go
问题
我正在创建一些变量在 B_test.go
中,并且我想在 A_test.go
中使用这些相同的变量。在 Go 语言中可以实现这个吗?我认为问题归结为在 go test
过程中是否可以从 B_test.go
导出函数。
示例:
在包 A_test.go
中:
package A
var from_B = B.ExportedVars()
在包 B_test.go
中:
package B
ExportedVars() []int {
return []int{0, 1)
}
运行 go test
会报错:
undefined B.ExportedVars
将 ExportedVars()
放在 B.go
而不是 B_test.go
中可以解决这个问题,但这不是我想要的。我希望它存在于测试文件中。
英文:
I'm creating some vars in B_test.go
and I want to use those same vars in A_test.go
. Can this be done in Go? I think the question boils down to whether I can export functions from B_test.go
during go test
only.
Example:
In package A_test.go
package A
var from_B = B.ExportedVars()
In package B_test.go
package B
ExportedVars() []int {
return []int{0, 1)
}
Running go test
gives
undefined B.ExportedVars
Putting ExportedVars()
in B.go
instead of B_test.go
solves the problem but this is not what I want. I want it to live in the test file.
答案1
得分: 2
包无法从其他包的测试文件中看到导出的符号,因为go
工具不会将这些文件构建到安装的包中。你可以使用构建约束来解决这个问题。
创建一个文件或多个文件,包含你想要导出的所有内容,而不使用_test.go
后缀。然后,在使用你选择的标签时,将它们标记为仅构建。
// +build export
package normal
var ExportedName = somethingInternal
当测试依赖于normal
包中的ExportedName
的包时,你需要在测试运行中添加-tags export
标志。
这对于其他各种原因也很有用,比如使用-tags debug
构建,可以添加额外的功能,如导入net/http/pprof
或expvar
。
英文:
Packages cannot see exported symbols from other package's test files, because the go
tools do not build those files into the installed package. One option you do have is to use build constraints.
Create a file or files that contain everything you want to export for whatever reason, without using the _test.go
suffix. Then mark them for build only when using your chosen tag.
// +build export
package normal
var ExportedName = somethingInternal
When testing a package dependent on this ExportedName
in package normal
, you will need to add the -tags export
flag to the test run.
This is also useful for various other reasons, like having a -tags debug
build, which can add extra functionality such as importing net/http/pprof
or expvar
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论