Testing is a critical ritual of modern software development practices. Go brings testing directly into the development cycle by offering an API and command-line tool to seamlessly create and integrate automated test code. Here we will cover the Go testing suite, including the following:
Prior to writing any test code, let's take a detour to discuss the tooling for automated testing in Go. Similar to the go build
command, the go test
command is designed to compile and exercise test source files in specified packages, as illustrated in the following command:
$> go test .
The previous command will exercise all test functions in the current package. Although it appears to be simple, the previous command accomplishes several complex steps, including:
When the go test
command targets multiple packages, the test tool generates multiple test binaries that are executed and tested independently, as shown in the following:
$> go test ./...
The test command uses the import path standard (see Chapter 6, Go Packages and Programs) to specify which packages to test. Within a specified package, the test tool will compile all files with the *_test.go
name pattern. For instance, assuming that we have a project that has a simple implementation of a mathematical vector type in a file called vec.go
, a sensible name for its test file would be vec_test.go
.
Traditionally, test files are kept in the same package (directory) as the code being tested. This is because there is no need to separate tests files, as they are excluded from the compiled program binary. The following shows the directory layout for a typical Go package, in this instance the fmt
package from the standard library. It shows all of the test files for the package in the same directory as the regular source code:
$>tree go/src/fmt/ ├── doc.go ├── export_test.go ├── fmt_test.go ├── format.go ├── norace_test.go ├── print.go ├── race_test.go ├── scan.go ├── scan_test.go └── stringer_test.go
Besides having a simpler project structure, keeping the files together gives test functions full visibility of the package being tested. This facilitates access to and verification of package elements that would otherwise be opaque to testing code. When your functions are placed in a separate package from the code to be tested, they lose access to non-exported elements of the code.
3.149.253.210