Chapter 15. Writing Tests
Since the 2000s, the widespread adoption of automated testing has probably done more to improve code quality than any other software engineering technique. As a language and ecosystem focused on improving software quality, it’s not surprising that Go includes testing support as part of its standard library. Go makes it so easy to test your code, there’s no excuse to not do it.
In this chapter, you’ll see how to test Go code, group tests into unit and integration tests, examine code coverage, write benchmarks, and learn how to check code for concurrency issues by using the Go data race detector. Along the way, I’ll discuss how to write code that is testable and why this improves our code quality.
Understanding the Basics of Testing
Go’s testing support has two parts: libraries and tooling. The testing
package in the standard library provides the types and functions to write tests, while the go test
tool that’s bundled with Go runs your tests and generates reports. Unlike many other languages, Go places its tests in the same directory and the same package as the production code. Since tests are located in the same package, they are able to access and test unexported functions and variables. You’ll see in a bit how to write tests that ensure that you are testing only a public API.
Note
Complete code samples for this chapter are found in the Chapter 15 repository.
Let’s write a simple function and then a test to make sure the function works. In the sample_code/adder ...
Get Learning Go, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.