在Golang中仅导出结构体以进行测试。

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

Export structure only for testing in Golang

问题

我有一个实用程序包,许多其他包都在使用它。我还创建了一些实现这些接口的测试结构,并将它们放在interfaces_test.go中。

我希望能够在其他包的*_test.go文件中导入这些测试结构。

我在http://golang.org/src/pkg/os/export_test.go中看到了类似的东西,但无论我尝试什么,都会出现类似于以下错误的错误:

go test something/mypackage
mypackage/ant_lat_lon_test.go:46: undefined: rutl.TestAntenner
FAIL	something/mypackage [build failed]

有办法可以做到吗?

英文:

I have a utility package that many other packages use. I also created some test structures that implement those interfaces. And I put them in interfaces_test.go

I'd like to be able to import those test structures in other packages in my *_test.go files.

I saw something like that in http://golang.org/src/pkg/os/export_test.go but whatever I try I get an error similar to this one:

go test something/mypackage
mypackage/ant_lat_lon_test.go:46: undefined: rutl.TestAntenner
FAIL	something/mypackage [build failed]

Is there a way to do it?

答案1

得分: 25

匹配*_test.go的文件只在测试它们所属的包时进行编译。如果你正在测试使用包B的包A,你将无法访问包B中的_test.go代码。

因此,有两个选项:

  1. 总是将测试支持代码编译到包B中。
  2. 如果测试支持代码只依赖于B的导出接口,请考虑将其拆分为一个单独的包。
英文:

Files matching *_test.go are only compiled when testing the package they are part of. If you are testing package A that uses package B, you won't have access to the _test.go code from package B.

So the two options are:

  1. Always compile the test support code into package B.
  2. If the test support code only depends on the exported interface of B, consider splitting it out into a separate package.

huangapple
  • 本文由 发表于 2014年3月9日 10:04:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/22277537.html
匿名

发表评论

匿名网友

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

确定