Golang tests in sub-directory

The Graceful Penguin picture The Graceful Penguin · Oct 5, 2013 · Viewed 65.2k times · Source

I want to create a package in Go with tests and examples for the package as subdirectories to keep the workspace cleaner. Is this possible and if so how?

All the documentation always puts the testing code in the same place as the other code, is this better in some way or just convention?

Answer

VonC picture VonC · Feb 12, 2014

Note that you can run go test "recursively": you need to list all the packages you want to test.

If you are in the root folder of your Go project, type:

go test ./...

The './...' notation is described in the section "Description of package lists" of the "command go":

An import path is a pattern if it includes one or more "..." wildcards, each of which can match any string, including the empty string and strings containing slashes.

Such a pattern expands to all package directories found in the GOPATH trees with names matching the patterns.

As a special case, x/... matches x as well as x's subdirectories.
For example, net/... expands to net and packages in its subdirectories.


If you keep your _test.go files in a subfolder, the 'go test ./...' command will be able to pick them up.
But:

  • you will need to prefix your exported variables and functions (used in your tests) with the name of your package, in order for the test file to be able to access the package exported content.
  • you wouldn't access non-exported content.

That being said, I would still prefer keep the _test.go file right beside the main source file: it is easier to find.