Golang Unit Test Coverage

ยท

2 min read

Golang has really good support for unit testing out of the box. With the go test CLI and the testing std library you can do almost *everything.

One of the niceties it provides is code coverage. You can run your tests with a flag -cover or you can even have to collect the coverprofile and spin up an interactive UI and check your code and what branches are covered with

# run tests and create a coverprofile
go test ./... -coverprofile=cover.out
# open the interactive UI to check the Coverage Repor
go tool cover -html=cover.out

You should see something similar to this for your code

Coverage Report UI

The red colour indicates that those branches are not covered at all by your unit tests and then with shades of green, you can see how much your code is covered.


What is this post about then?

All this is good, what Golang provides right away is at least amazing. But what I have found missing, is coverage threshold.

What is coverage threshold?

If you are coming from the js ecosystem you might have encountered this in jest. With a coverage threshold, if your test coverage is less than a specified percentage, they will fail even if they are successful.

There is a long debate about whether high code coverage or what percentage of code coverage is the best. This post is not covering this debate. If you are interested I could do it in a separate post and share my thoughts.

Code coverage "tracking" can be useful, in many different scenarios. Adding a new feature, you write your unit tests but you miss covering some branches. If your coverage goes below the acceptable threshold you will be notified right away when running your tests. If someone is contributing to your team's project, it can show that you are expecting at least some basic unit tests for the code he wrote.

Coverage

So I took the opportunity and wrote a small util library, that does exactly that.

Given a threshold number if your package is below that, then it will fail your tests

You can find the code and the library in coverage. Have a look and tell me what you think.

* Of course some useful libraries can help you with boilerplate code like testify or go-snaps (shameless plug ๐Ÿ˜…)


Thanks for reading โค๏ธ