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 to keep the _test.go
file right beside the main source file: it is easier to find.
2022: For code coverage:
go test -coverpkg=./... ./...
See "How to plot Go test coverage over time" from Frédéric G. MARAND and fgmarand/gocoverstats
to produce aggregate coverage statistics for CI integration of Go projects.
Also, go-cover-treemap.io
is fun.
March 2023: As documented in "Code coverage for Go integration tests":
With the 1.20 release, Go’s coverage tooling is no longer limited to package tests, but supports collecting profiles from larger integration tests.
Example:
$ go build -cover -o myprogram.exe myprogram.go
$ mkdir somedata
$ GOCOVERDIR=somedata ./myprogram.exe
I say "Hello, world." and "see ya"
$ ls somedata
covcounters.c6de772f99010ef5925877a7b05db4cc.2424989.1670252383678349347
covmeta.c6de772f99010ef5925877a7b05db4cc
See Go 1.20 Cover.
As noted by kbolino in the comments:
You can put your tests in a separate package without putting them in a separate directory.
Test files for package foo can be in package foo_test
and still be in the same directory, while also not having any access to unexported (private) members of package foo
.