Code Coverage in Go
Code Coverage helps you to validate your code, it helps a lot when you make incremental changes and need to make sure that all previous functionality are indeed intact. In GO also you can write code for code coverage and calculate the same.
How to Measure Code Coverage
Command | Description |
---|---|
go test -cover . |
Gets basic coverage statistics for a single package |
go test ./... -coverprofile cover.out |
Creates Cover Profile for overall code coverage for multiple packages |
go tool cover -func cover.out |
Gives you code coverage for every single package within your project |
go test ./... -coverprofile=cover |
Gives you a coverage profile, then use below command to read it |
go tool cover -html=cover |
Gives you code coverage in HTML File |
go test -cover .
Command
go test -cover .
command will only give you basic coverage statistics for a single package. That is if you run this command in package service
it will only calculate coverage for service
package.
go test ./... -coverprofile cover.out
Command
go test ./... -coverprofile cover.out
command will give you the overall code coverage for multiple packages. Run it from main package folder location. Then you can run below command to view the code coverage percentage.
go tool cover -func cover.out
Command
go tool cover -func cover.out
command will give you the code coverage for every single function/method in a package within your project. This command will only work if cover.out
is generated using above command.
go test -coverprofile=cover
Command
go test -coverprofile=cover
command will give you the code coverage for a single package. You can then use bottom most command to read it.
go test ./... -coverprofile=cover
Command
go test ./... -coverprofile=cover
command will give you the code coverage for all the packages. You can then use below command to read it.
go tool cover -html=cover
Command
go tool cover -html=cover
command will generate HTML representation of coverage profile that we just created in above command.
Above command will give you below output
For demo purpose you can use this code