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.

bash
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.

bash
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:

bash
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:

bash
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

  1. Run tests with coverage:
    bash
    go test -coverprofile=coverage.out ./...
  2. View coverage report in the terminal:
    bash
    go tool cover -func=coverage.out
  3. 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.

bash
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!