Go: tests with HTML coverage report

Kanan Rahimov
Jan 2 · 2 min read
Tests result viewed as an HTML page.

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 ./...
as an example project, I am using a popular cobra package (spf13/cobra)

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

go test -cover ./...
test coverage result

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
a detailed coverage result

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
a detailed coverage report viewed as an HTML report

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:

GOCOVER=$(GO) tool cover
.PHONY: test/cover
$(GOTEST) -v -coverprofile=coverage.out ./...
$(GOCOVER) -func=coverage.out
$(GOCOVER) -html=coverage.out

Kanan Rahimov

Written by

Software Engineer. Author @CoderVlogger. Check https://kenanbek.github.io/ for more posts and updates.

More From Medium

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade