如何打包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

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

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

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.

How do I solve this?


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

Following go issue 8279, I have seen dummy files added, as in tommie/acme-cli commit 479f8c7

outer/outer.go

// +build ignore+
package outer

See if that could help here, as a workaround.


As commented above, using a test helper code in an internal package (from Go 1.4+) is another option, since no client from this project would be able to access said helper. See design document.
You can see it used in a typical Go project layout.

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.

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