When writing tests, it is often important to know how much of the actual code is getting exercised (or covered) by the tests. That number is an indication of the penetration of the test logic against the source code. Whether you agree or not, in many software development practices, test coverage is a critical metric as it is a measure of how well the code is tested.
Fortunately, the Go test tool comes with a built-in coverage tool. Running the Go test command with the -cover
flag instruments the original source code with coverage logic. It then runs the generated test binary, providing a summary of the overall coverage profile of the package, as shown in the following:
$> go test -cover PASS coverage: 87.8% of statements ok github.com/vladimirvivien/learning-go/ch12/vector 0.028s
The result shows a well-tested code with a coverage number of 87.8%
. We can use the test tool to extract more details about the section of the code that is tested. To do this, we use the -coverprofile
flag to record coverage metrics to a file, as shown:
$> go test -coverprofile=cover.out
Once the coverage data is saved, it can be presented in a textual tab-formatted table using the go tool cover
command. The following shows a partial output of the breakdown of the coverage metrics for each tested function in the coverage file generated previously:
$> go tool cover -func=cover.out ... learning-go/ch12/vector/vec.go:52: Eq 100.0% learning-go/ch12/vector/vec.go:57: Eq2 83.3% learning-go/ch12/vector/vec.go:74: Add 100.0% learning-go/ch12/vector/vec.go:85: Sub 100.0% learning-go/ch12/vector/vec.go:96: Scale 100.0% ...
The cover
tool can overlay the coverage metrics over the actual code, providing a visual aid to show the covered (and uncovered) portion of the code. Use the -html
flag to generate an HTML page using the coverage data gathered previously:
$> go tool cover -html=cover.out
The command opens the installed default web browser and displays the coverage data, as shown in the following screenshot:
The preceding screenshot shows only a portion of the generated HTML page. It shows covered code in green and code that is not covered in red. Anything else is displayed in gray.
3.14.145.82