Go: tests with HTML coverage report

No matter what, tests are essential. Coverage reports help us to write better tests. Go has extensive support for both. In this article, I will share examples of how you run tests and get coverage reports.
First, let’s start with running tests. Normally I use the following command to run tests:
go test ./...

This command will run tests for the whole project. To include coverage reports, we should add -cover option.
go test -cover ./...

The result of this command will include coverage reports per source file. As you can see, it provides minimal information.
To get detailed information on the coverage, we can use the combination of these following commands:
go test -coverprofile=coverage.out ./...
go tool cover -func=coverage.out

In the first command, we use -coverprofile to save coverage results to the file. And then, we print detailed results by using Go’s cover tool.
By using the same cover tool, we can also view coverage result as an HTML page:
go tool cover -html=coverage.out

The coverage tool also includes three different coverage modes. You can select coverage mode by using -covermode option:
go test -covermode=count -coverprofile=coverage.out
There are three different cover modes:
- set: did each statement run?
- count: how many times did each statement run?
- atomic: like count, but counts precisely in parallel programs
For more information on the topic, please check Go’s blog:
We also can combine these commands as a Makefile target:
GO=go
GOCOVER=$(GO) tool cover.PHONY: test/cover
test/cover:
$(GOTEST) -v -coverprofile=coverage.out ./...
$(GOCOVER) -func=coverage.out
$(GOCOVER) -html=coverage.out
If you’ve any feedback, feel free to tell me what I can improve, or provide better examples.
Follow me on Twitter and GitHub for more code snippets, posts, updates. Happy coding! :)
My YouTube Channel: https://youtube.com/CoderVlogger
Thanks!