Chapter 12. Code Testing

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:

  • The Go test tool
  • Writing Go tests
  • HTTP testing
  • Test coverage
  • Code benchmark

The Go test tool

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:

  • The compilation of all test files found in the current package
  • Generating an instrumented binary from the test file
  • Executing the test functions in the code

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 ./... 

Test file names

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.

Test organization

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.253.210