How do you measure test coverage in Go unit tests?

How to measure test coverage in Go - Stack OverflowHas anyone successfully generated code coverage for Go unit tests? I’m having trouble finding a tool for that on the web. Specifically, I’m looking for a solution related to go test coverage.

Hey Sueelak,

Here is your Answer,

Using go test with Coverage Flags: Go provides built-in support for code coverage via the go test command. You can generate a coverage report by running:

go test -coverprofile=coverage.out

This command runs your tests and writes a coverage profile to the file coverage.out. You can then view a detailed coverage report by using:

go tool cover -html=coverage.out

This will open an HTML report in your default web browser showing which parts of your code are covered by tests.

Hey Suneelak,

Using cover Tool: Go’s cover tool is included with the Go distribution and can be used to produce coverage reports. For a more detailed view, you can use:

go test -coverprofile=coverage.out go tool cover -func=coverage.out

The -func flag provides a summary of the coverage for each function in your code, showing the percentage of code covered by tests.

Hello Suneelak,

Integrating with CI/CD Tools:

Many CI/CD tools and services support Go code coverage and can integrate with your testing setup. For instance, tools like Codecov(https://codecov.io/) or Coveralls(https://coveralls.io/) can automatically upload your coverage reports and provide visual dashboards and insights. You typically need to upload your coverage report as part of your CI/CD pipeline configuration. For example, after generating the coverage.out file, you can use codecov to upload it:

bash <(curl -s https://codecov.io/bash)

This command uploads the coverage report to Codecov, where you can view detailed coverage information.