如何打包golang测试帮助程序代码? [英] How do I package golang test helper code?

查看:88
本文介绍了如何打包golang测试帮助程序代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的golang库中有一些测试帮助程序代码,我想在各种子包中进行测试时使用这些代码.但是,我遇到了一个障碍:

I have some test helper code in my golang library that I want to use when testing in various subpackages. However, I've hit a snag:

outer
|
+- test_helpers_test.go
|
+- inner
   |
   +- something.go
   +- something_test.go

要使用 test_helpers_test.go 中的代码,我必须导入外部包.但是,当我从 something_test.go 导入外包装时,它抱怨测试中不允许导入周期"

To use the code in test_helpers_test.go, I have to import the outer package. But when I import the outer package from something_test.go, it complains "import cycle not allowed in test"

因此,我尝试为共享测试助手创建一个程序包:

So I tried making a package for the shared test helpers:

outer
|
+- test
|  |
|  +- test_helpers_test.go
|
+- inner
   |
   +- something.go
   +- something_test.go

现在它抱怨"/home/karl/Projects/outer/test中没有非测试Go文件"

And now it complains "no non-test Go files in /home/karl/Projects/outer/test"

我不想称其为 test_helpers.go ,因为它是我的测试代码的一部分,而不是我的库代码的一部分.我不想将该代码发送到库中.

I don't want to call it test_helpers.go because it's part of my testing code, not my library code. I don't want to ship that code in the library.

我该如何解决?

更新:我可以通过在 test 目录中创建一个 dummy.go 文件来解决此问题,但是现在存在一个新问题:导入软件包导入其测试代码!所以现在我得到: ./something_test.go:12:2:undefined:test.AssertDoesPanic

Update: I can work around the issue by creating a dummy.go file in the test directory, but now there's a new problem: Importing a package DOESN'T import its test code! So now I get: ./something_test.go:12:2: undefined: test.AssertDoesPanic

推荐答案

您是正确的,因为您不能从另一个包中导入测试代码,所以您的助手功能必须放入适当的代码文件中,而不是测试文件中.

You are right that you cannot import test code from another package so your helper functions have to go into proper code files rather than test files.

如果不是从非测试代码中导入的,则不会将其内置到最终的二进制文件中.

If it isn't imported from your non-test code then it won't be built into the final binary.

作者倾向于调用软件包 ... test 来表明它只是测试助手,例如标准库中的 httptest zaptest 来自开源.

Authors tend to call the package ...test to indicate it is just test helpers, for instance httptest from the standard library or zaptest from open source.

https://golang.org/pkg/net/http/httptest/ https://godoc.org/go.uber.org/zap/zaptest

这篇关于如何打包golang测试帮助程序代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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