Measure coverage without overclaiming
Measure coverage without overclaiming
Coverage reports which instrumented statements ran during tests. Go’s go test -cover reports statement coverage, not exhaustive path coverage or correctness. Use coverage to find missing cases, not as a substitute for meaningful assertions. Run the shown commands in each fresh module.
Create the files shown below in a fresh directory, then run go test -count=1 -v ./... there. The separator lines are file labels, not source code. Go 1.23 is used for these local examples.
--- go.mod ---module example.test/lesson
go 1.23
--- calc.go ---package calc
func Sign(n int) int { if n < 0 { return -1 } if n > 0 { return 1 } return 0}
--- calc_test.go ---package calc
import "testing"
func TestSign(t *testing.T) { if Sign(2) != 1 { t.Fatal("positive") }}Run go test -cover -count=1. The positive test passes but the negative and zero returns are not exercised. Expect a coverage percentage below 100%. A coverage profile can be created with go test -coverprofile=cover.out and summarized with go tool cover -func=cover.out. The profile is a generated local file.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestSignCover the missing return paths
--- go.mod ---module example.test/lesson
go 1.23
--- calc.go ---package calc
func Sign(n int) int { if n < 0 { return -1 } if n > 0 { return 1 } return 0}
--- calc_test.go ---package calc
import "testing"
func TestSign(t *testing.T) { for _, c := range []struct{ n, want int }{{-3, -1}, {0, 0}, {3, 1}} { if Sign(c.n) != c.want { t.Errorf("input %d", c.n) } }}Run go test -cover -count=1 again in the second module. For this function, all statements run and coverage reaches 100%. That still does not establish correct behavior for every integer or prove there are no defects. Coverage counts execution even when assertions are missing.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestSignTry it locally
Write a function Max(a,b int) int with two return paths. Test (1,2), (3,1), and (4,4). Run go test -cover. Use a fresh module with the same go.mod shown above; run go test -count=1 -v ./...
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Testing fundamentals 06: Measure coverage without overclaiming
Check the lesson objective before moving on.
What does Go statement coverage measure?
What does 100% statement coverage prove?