Create an HTML Test Coverage Report in Go

We can generate a unit test coverage report in Golang using the following commands and tools which are included with the language.

To run unit tests with coverage collection use:

go test -covermode=count -coverpkg=./... -coverprofile cover.out -v ./...

The coverpkg parameter is needed for the code coverage to include packages and not just the top level files in the project directory.

Generate the visual coverage HTML files using:

go tool cover -html cover.out -o cover.html

If you are using a Makefile on macOS we can add a command to run all of this together in order and open the page in a browser:

test-coverage:
  go test -v ./... -covermode=count -coverpkg=./... -coverprofile coverage/coverage.out
  go tool cover -html coverage/coverage.out -o coverage/coverage.html
  open coverage/coverage.html

Then run:

make test-coverage

This will open the very nice coverage report HTML page in a browser.