英文:
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
代码。
因此,有两个选项:
- 总是将测试支持代码编译到包B中。
- 如果测试支持代码只依赖于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:
- Always compile the test support code into package B.
- If the test support code only depends on the exported interface of B, consider splitting it out into a separate package.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论