You measure test coverage in Go by running the go test command with the -cover flag to get a percentage, or -coverprofile to generate a detailed report file for analysis. For a visual breakdown by package and file, pipe that profile into go tool cover.
To get a quick percentage for your entire module, run:
go test -cover ./...
This outputs a single line like coverage: 85.2% of statements. If you need to see exactly which lines are missing coverage, generate a profile file and open it in your browser:
go test -coverprofile=coverage.out ./...
go tool cover -html=coverage.out
The second command opens an HTML report in your default browser, highlighting covered lines in green and uncovered lines in red. You can also filter by specific packages or use the -covermode=count flag to see how many times each line was executed, which helps identify hot paths in your code.
For CI/CD pipelines, it's common to enforce a minimum threshold. You can parse the output of go test -cover or use tools like gocov and gocov-xml to generate coverage reports compatible with Jenkins, GitHub Actions, or Codecov. A typical GitHub Actions step might look like this:
- name: Test
run: go test -v -cover ./... -coverprofile=coverage.out
- name: Upload Coverage
uses: codecov/codecov-action@v3
with:
files: ./coverage.out
Remember that coverage metrics measure execution, not correctness. A high percentage doesn't guarantee your tests are meaningful; you still need to ensure your assertions actually validate the expected behavior. Focus on covering edge cases and critical logic paths rather than chasing 100% coverage on trivial getters or setters.