在Go包中放置测试的共享代码的位置? [英] Where to put shared code for tests in a Go package?

查看:141
本文介绍了在Go包中放置测试的共享代码的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个文件的Go包。在Go标准中,我为包中的每个源文件创建了一个关联的测试文件。

在我的情况下,不同的测试使用相同的测试帮助功能。我不希望这些函数在包源文件中,因为它仅用于测试目的。我也想避免在每个测试文件中复制这些代码。



我应该在所有测试源文件之间共享此代码,而不是包的一部分?

解决方案

您只需将其放入任何测试文件即可。使用相同包子句的测试文件属于相同的测试包,并且可以在不带任何 import 语句的情况下引用彼此的导出的未导出的标识符。



另外请注意,您无需为每个<$ c $创建单独的 _test.go 文件c> .go 文件;并且您可以在包中没有匹配 xx.go 文件的情况下拥有 xx_test.go 文件。



例如,如果您正在编写包 a ,包含以下文件:

  a / 
a.go
b.go
a_test.go
b_test.go

对于黑盒测试,您可以使用软件包a_test 包含在 a_test.go b_test.go 中的子句。在文件 a_test.go 中有一个 func util(),你可以在 b_test .go 也是。



如果您正在编写白盒测试,您可以使用 package a ,并且可以从 b_test.go a_test.go 中声明的任何标识符

请注意,如果 a_test.go b_test.go 不匹配(例如 a_test.go 使用 package a b_test.go 使用 package a_test ),那么它们将属于不同的测试包,然后您不能使用彼此声明的标识符。


I have a Go package with multiple files. As of Go standard I am creating an associated test file for each source file in the package.

In my case the different tests use the same test helping functions. I don't want these functions to be in the package source files because it is only used for testing purpose. I also would like avoiding replicating this code in each test file.

Where should I put this code shared between all the test source files and not part of the package ?

解决方案

You just put it in any of the test files and that's all. Test files using the same package clause belong to the same test package and can refer to each other's exported and unexported identifiers without any import statements.

Also note that you're not required to create a separate _test.go file for each of the .go files; and you can have an xx_test.go file without having a "matching" xx.go file in the package.

For example if you're writing package a, having the following files:

a/
    a.go
    b.go
    a_test.go
    b_test.go

For black-box testing you'd use the package a_test package clause in a_test.go and b_test.go. Having a func util() in file a_test.go, you can use it in b_test.go too.

If you're writing white-box testing, you'd use package a in the test files, and again, you can refer any identifiers declared in a_test.go from b_test.go (and vice versa) without any imports.

Note that however if the package clauses in a_test.go and b_test.go do not match (e.g. a_test.go uses package a and b_test.go uses package a_test), then they will belong to different test packages and then you can't use identifiers declared in one another.

这篇关于在Go包中放置测试的共享代码的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆