How to measure code coverage in Golang?

前端 未结 11 2051
花落未央
花落未央 2020-12-22 16:12

Has anyone succeeded in generating code coverage for Go unit tests? I can\'t find a tool for that on the web.

11条回答
  •  攒了一身酷
    2020-12-22 17:14

    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:

    enter image description here

    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.

提交回复
热议问题