Go · Unit testing · Coverage

Unit testing coverage in Go

Before I embarked on my Go development career, I was a (not very good) Python developer. Unit testing was mandated at the company I worked at, but there was no (at that time) really simple way to get any idea what code you had, and hadn’t covered with the tests you had written. It was very much reliant on the developer’s experience and understanding of the test being written as to how much of the code was being tested, and which parts weren’t.

Sure, a developer should understand what they’re doing, but, that’s not always the case.

When I was introduced to Go, one of the first things that I discovered was the coverage reporting that is baked into Go. The Go Blog has a fine article on Go test coverage, which I strongly recommend for a more in depth understanding.

Sure, you can execute a command that gives you a percentage count of code covered, but that’s little help (except on CI/CD systems where PR acceptance might depend on some arbitrary metric).

The following incantation will present a web-page with covered code highlighted in Green, uncovered code in Red, and code that doesn’t get counted in the coverage statistics is Grey.

go test -coverprofile=coverage.out
go tool cover -html=coverage.out

That’s great for starting out, but it’s clunky, first you execute a command that checks what code is covered, and produces a report (coverage.out) in the working directory, then you execute a command that processes that report into a pretty html report for you.

In almost every code editor that supports Go it’s possible to see the coverage. With Vim-go the command is :GoCoverage which gives the following (note I have two panes open one to show before coverage, and one to show after).

Note: Colour blind people can change the colours used in Vim-go with :highlight goCoverageCovered ctermfg=12

This simple feature makes code coverage obvious and simple to work with. The developer can see exactly what code has been covered, and can experiment with their tests (table tests right!) to get their code properly tested. There are no excuses for Go developers to hide behind when it comes to questions about what code their tests actually cover.

Published:
comments powered by Disqus