This chapter covers
- Exploring idiomatic principles with packages
- Satisfying the standard library interfaces
- Writing and running tests using the tools provided by Go
- Using table-driven testing and subtests to improve maintainability
- Writing example tests to generate runnable documentation
Automated tests ensure that code works today and will continue to work in the future. Focusing on testing right away builds a solid mindset for the remainder of the book. This chapter covers testing fundamentals; the following chapters explore this topic in greater depth.
We’ll explore how to write and test a simple URL parser package called url
, a replica of the standard library’s url
package with the same name. Although simple, it shows the proper way to name packages and their items, handle errors, and implement interfaces from the standard library. When we have its basic version in place, we’ll test the package.
After learning the fundamentals of testing in Go, we’ll explore table-driven tests to reduce duplication. Although table-driven testing is helpful, it has some pitfalls, which we’ll address using subtests. Last, we’ll learn how to generate documentation using example tests. Chapter 3 dives into measuring test coverage, benchmarking, and optimization.