Code coverage measures the percentage of statements in a target package that tests execute. It helps reveal testing gaps during development, but 100% coverage is not always realistic, especially for exceptional conditions such as file-access or network failures. section 8.5.7
Use Go’s coverage tooling as a practical review loop:
- Run `go test -cover` to execute tests and report the percentage of covered statements. section 8.5.7
- Run `go test -coverprofile=coverage.out` to save annotated coverage data for later inspection. section 8.5.7
- Run `go tool cover -html=coverage.out` to inspect uncovered and covered source lines in a browser. section 8.5.7
- Treat uncovered code as a prompt to assess missing behavior, rather than as a quality score by itself. section 8.5.7 section 8.8
Coverage exposes an error-recovery gap
A calculator package initially reports 93.8% coverage. Additional tests exercise storage after an invalid division and raise coverage to 100%, but the tests fail because Calculate retains an old internal error. Resetting that error before successful operations makes the tests pass. The example shows how coverage can uncover an untested path and help drive a concrete bug fix, while still not proving overall correctness. section 8.5.7
Listing 8.22 Output of go test -cover for the basicmath package
$ go test -cover PASS coverage: 93.8% of statements ok basicmath 0.195s
View a representative `go test -cover` result showing the package status, execution time, and statement percentage. section 8.5.7
Listing 8.23 Using go test -coverprofile to generate a coverage profile file
$ go test -coverprofile=coverage.out PASS coverage: 93.8% of statements ok basicmath 0.195s $ tail -n 3 coverage.out #1 goinaction.book/ch09/basicmath/calculator.go:50.18,52.3 1 0 goinaction.book/ch09/basicmath/calculator.go:53.2,53.18 1 1 goinaction.book/ch09/basicmath/calculator.go:57.35,59.2 1 1
Inspect the generated coverage profile and its annotated source ranges before opening the visual report. section 8.5.7
Listing 8.24 Opening the code coverage in the browser
$ go tool cover -html=coverage.out
Open the coverage profile through Go’s built-in browser viewer for source-level highlighting. section 8.5.7













