How to Run Go Tests with Coverage Percentage

· 146 words · 1 minute read

Go has a brilliant built in testing package, which although it is quite raw, it is very powerful. It also has the ability to show the test coverage as a percentage of the code base. Which is very useful to get perspective of a project and to know perhaps which areas need improvement.

You can see the test coverage by using the -coverprofile parameter on the test command.

1
2
3
4
5
go test -coverprofile cp.out

# PASS
# coverage: 60.2% of statements
# ok      yourpackage  1.372s

This is great, but even better is being able to visualise the test coverage. You can see which code is run during testing and which code is not by loading the cover profile in a browser. To do this, use this command:

1
go tool cover -html=cp.out

Which will produce something like this (although I’ve cropped it down):

Code Example

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!