如何从一个测试包中导出数据,并在另一个测试包中使用它们?

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

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/pprofexpvar

英文:

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

huangapple
  • 本文由 发表于 2014年12月23日 09:00:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/27612721.html
匿名

发表评论

匿名网友

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

确定