在Go包中,将共享代码放在哪里进行测试?

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

Where to put shared code for tests in a Go package?

问题

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

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

我应该把这段代码放在哪里,以便在所有测试源文件之间共享,而不是作为包的一部分?

英文:

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 ?

答案1

得分: 8

你只需要将它放在任何一个测试文件中就可以了。使用相同包声明的测试文件属于同一个测试包,可以在没有任何import语句的情况下引用彼此的导出和非导出标识符。

另外,请注意,你不需要为每个.go文件创建单独的_test.go文件;你可以在包中有一个xx_test.go文件,而没有相应的“匹配”xx.go文件。

例如,如果你正在编写包a,有以下文件:

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

对于黑盒测试,你可以在a_test.gob_test.go中使用package a_test包声明。在a_test.go文件中有一个func util(),你也可以在b_test.go中使用它。

如果你正在编写白盒测试,你可以在测试文件中使用package a,同样,你可以在b_test.go中引用在a_test.go中声明的任何标识符(反之亦然),而无需导入任何内容。

请注意,如果a_test.gob_test.go中的包声明不匹配(例如,a_test.go使用package a,而b_test.go使用package a_test),那么它们将属于不同的测试包,你将无法在彼此之间使用声明的标识符。

英文:

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.

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

发表评论

匿名网友

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

确定