8 Testing And Tooling
This chapter covers
- Unit Testing With The
testing
Package - Test-Driven Development.
- Code Coverage
- Test Fixtures and Helpers
- Benchmarking
- Fuzzing
Testing sometimes gets a bad rap as a chore or an afterthought—something to be added later, after the difficult work of solving problems is done. Often, you will hear programmers talk about testing in terms of "peace of mind", meaning that tests can help verify that your software continues to work as expected, even as new features are added or parts of the underlying logic are changed. If the tests keep passing, the reasoning goes, your code is still functioning as intended, or at least in all the ways that matter.
Peace of mind is certainly an important benefit of testing, but if all you are concerned with is verifying your code after the fact, then you’re missing out on a lot of what testing can do for you, especially in a language with a solid set of tooling like what is available in Go.
Rather than being defensive, tests can be proactive, and you can wield them like a scalpel instead of a shield, identifying and targeting areas for improvement in existing code.
The extended tooling around profiling and testing remains one of Go’s enduring strengths and, when combined with benchmarking, enables you to identify and target areas for performance improvement. By creating a benchmark and adding a couple of flags, you can get targeted stats on CPU usage and memory allocation, sometimes down to the individual line.