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:
The Go Blog
Rob Pike 2 December 2013 Introduction From the beginning of the project, Go was designed with tools in mind. Those…
We also can combine these commands as a Makefile target:
GOCOVER=$(GO) tool cover.PHONY: test/cover
$(GOTEST) -v -coverprofile=coverage.out ./...