Test Coverage
Start with Test Coverage
In this lesson, explore test coverage through one small Go program, and connect its output to the language rules behind it.
What you’ll learn
- Explain the main purpose of test coverage.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Go measures which statements are exercised when running tests with -cover or -coverprofile. Coverage points to code paths worth examining; a high percentage does not prove tests make good assertions.
Use coverage information to find untested branches and add behavior-focused cases instead of chasing a percentage in isolation.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Tools, syntax and practical notes
Commands: go test -cover ./..., go test -coverprofile=cover.out ./..., go tool cover -func=cover.out. Reference: Code coverage for Go integration tests.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func category(n int) string {
if n < 0 {
return "negative"
}
if n == 0 {
return "zero"
}
return "positive"
}
func main() { fmt.Println(category(-1), category(0), category(1)) }
Output
negative zero positiveTrace what the program does
The three inputs exercise all three outcomes. Coverage instrumentation in go test can show whether tests, rather than main, execute these branches.
Avoid common mistakes
- Statement coverage does not guarantee that conditions or edge cases are correct.
- Coverage from running main.go is not the same as go test coverage.
Try it yourself
Write three TestCategory cases and run go test -coverprofile=cover.out followed by go tool cover -func=cover.out.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Test Coverage in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.