Testing Workflow with Coverage Reports
Intermediate10 minTrending
Run Go tests with race detection, generate coverage reports, and visualize coverage in the browser.
Prerequisites
- -Go 1.21+ installed
- -A Go project with tests
Steps
1
Run all tests with verbose output
Execute the full test suite with verbose output and race detection enabled.
$ go test ./... -v -race
The -race flag detects data races at runtime. Always use it in CI.
2
Generate a coverage profile
Run tests and output a coverage profile file for analysis.
$ go test ./... -coverprofile=coverage.out -covermode=atomic
3
View coverage summary by function
Display a breakdown of coverage percentage per function.
$ go tool cover -func=coverage.out
4
Open coverage report in the browser
Generate an HTML coverage report and open it for visual inspection.
$ go tool cover -html=coverage.out -o coverage.html
Green lines are covered, red lines are not. Focus on uncovered branches in critical paths.
5
Enforce minimum coverage threshold
Parse coverage output and fail the build if total coverage is below a threshold.
$ go test ./... -coverprofile=coverage.out && total=$(go tool cover -func=coverage.out | grep total | awk '{print $3}' | tr -d '%') && echo "Coverage: ${total}%" && [ $(echo "$total >= 70" | bc) -eq 1 ] || (echo 'FAIL: coverage below 70%' && exit 1)
Set a realistic threshold. Forcing 100% coverage leads to low-value tests.
Full Script
FAQ
Discussion
Loading comments...