In Go, you can check test coverage using the built-in Go testing tool. Test coverage measures the percentage of your code that is exercised by your tests. The go test
command provides an option to generate coverage reports.
Here’s how you can check coverage in Go:
1. Generate Test Coverage
You can use the go test
command with the -cover
flag to generate a basic coverage report.
go test -cover ./...
-cover
: Generates a coverage report../...
: Tests all packages in the current directory and subdirectories.
This command will output the coverage percentage in the terminal.
2. Detailed Coverage Report
If you want to generate a detailed coverage report, including which lines are covered, you can use the -coverprofile
flag.
go test -coverprofile=coverage.out ./...
- This command runs the tests and outputs the coverage information into a file named
coverage.out
.
3. View Coverage Report
Once you’ve generated the coverage profile (coverage.out
), you can view it in a more readable format by using the go tool cover
command.
To view a text-based summary in the terminal:
go tool cover -func=coverage.out
This will output the coverage percentage for each function and the total coverage.
4. Visualize Coverage in HTML
If you want a more visual and interactive way to see which lines are covered by your tests, you can generate an HTML report:
go tool cover -html=coverage.out
This will open a web page in your browser showing the coverage for each line of code, with covered lines highlighted in green and uncovered lines in red.
5. Example Workflow
- Run tests with coverage:
bash
go test -coverprofile=coverage.out ./...
- View coverage report in the terminal:
bash
go tool cover -func=coverage.out
- Generate and view an HTML coverage report:
bash
go tool cover -html=coverage.out
6. Coverage Threshold (Optional)
You can specify a minimum coverage threshold by using -covermode
and -coverpkg
flags. If the test coverage is below this value, the tests will fail.
go test -covermode=count -coverpkg=./... -coverprofile=coverage.out
Summary:
- Basic Coverage:
go test -cover ./...
- Detailed Coverage:
go test -coverprofile=coverage.out ./...
- View Coverage:
go tool cover -func=coverage.out
- Visualize Coverage:
go tool cover -html=coverage.out
This is how you can check test coverage in Go and ensure your code is adequately tested!