DEV Community

Georgios Kampitakis
Georgios Kampitakis

Posted on • Edited on

Go Unit Test Coverage

Go 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
Enter fullscreen mode Exit fullscreen mode

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 Go 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 js ecosystem you might have encountered this in jest. With a coverage threshold, if your tests are less than a specified percentage, even if they are successful they will fail.

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 ❤️

Top comments (0)