Has anyone succeeded in generating code coverage for Go unit tests? I can\'t find a tool for that on the web.
Inspired by the help menus and other answers to this question, just run:
f=cover.out; if [ -f $f ]; then rm $f; fi; go test ./... -coverprofile $f && \
go tool cover -html $f && \
rm $f
In addition to the good answers above, I find these three lines to be the simplest way to get it (which includes all packages):
go test -v -coverprofile cover.out ./YOUR_CODE_FOLDER/...
go tool cover -html=cover.out -o cover.html
open cover.html
Note that in the HTML file you will find a dropdown button that will direct you to all files.
A quick and easy way is to use the coverage tool that comes with built-in go :
$ go test -coverprofile cp.out // Emits the coverage in one liner percentage wise
After you execute the above command, if you wish to visually see the code coverage (like covered statements and missed etc)
$ go tool cover -html=cp.out
Note : You need to execute the above commands in the folder where you wish to see coverage
Go comes with awesome tool for testing and coverage. Although all Go tools are well documented go tool cover -help
I would suggest reading The cover story article on the official Go blog. It has plenty of examples and I strongly recommend it!
I have this function in my ~/.bash_profile. (you can just paste it in the terminal to give it a try).
cover () {
t="/tmp/go-cover.$$.tmp"
go test -coverprofile=$t $@ && go tool cover -html=$t && unlink $t
}
Then just cd
into a go project/package folder and type cover
.
This opens a visual tool in browser which shows you the tested and untested code for each file in the current package. Very useful command! I strongly recommend it for finding what is not 100% tested yet! The shown results are per file. From a drop down in top-left you can see results for all files.
With this command you can also check the coverage of any package for example:
cover fmt
The output in terminal from this command would be:
ok fmt 0.031s coverage: 91.9% of statements
In addition to that in your browser you will see this tool showing in red all lines of code which are not covered with tests:
It is also possible to just save the html coverage file instead of opening it in a browser. This is very useful in cases when your tests + coverage is run by CI tool like Jenkins. That way you can serve the coverage files from a central server and the whole team will be able to see the coverage results for each build.
If you are using VSCode this functionality is supported out the box ( But disabled by default )
Just turn on test on save + coverage reporting
https://github.com/microsoft/vscode-go/wiki/On-Save-features
It will even show in your editor which lines are not covered which is super handy.