Search code examples
unit-testingtestinggocode-coverage

How to measure test coverage in Go


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


Solution

  • Note that Go 1.2 (Q4 2013, rc1 is available) will now display test coverage results:

    One major new feature of go test is that it can now compute and, with help from a new, separately installed "go tool cover" program, display test coverage results.

    The cover tool is part of the go.tools subrepository. It can be installed by running

    $ go get golang.org/x/tools/cmd/cover
    

    The cover tool does two things.

    • First, when "go test" is given the -cover flag, it is run automatically to rewrite the source for the package and insert instrumentation statements. The test is then compiled and run as usual, and basic coverage statistics are reported:

      $ go test -coverprofile fmtcoverage.html fmt ok fmt 0.060s coverage: 91.4% of statements $

    • Second, for more detailed reports, different flags to "go test" can create a coverage profile file, which the cover program, invoked with "go tool cover", can then analyze.

    Frank Shearar mentions:

    The latest versions of Go (2013/09/19) use:

    go test -coverprofile <filename> <package name>
    

    Details on how to generate and analyze coverage statistics can be found by running the commands

    $ go help testflag
    $ go tool cover -help
    

    Ivan Black mentions in the comments:

    go test -coverprofile cover.out and then
    go tool cover -html=cover.out opens cover.out in your default browser

    I don't even want to wait for the browser to open, so I defined this alias:

    alias gc=grep -v -e " 1$" cover.out
    

    That I just type gc, and have a list of all the lines not yet covered (here: with a coverage.out line not ending with " 1").


    Update 2022, possibly for Go 1.19

    proposal: extend Go's code coverage testing to include applications

    While the existing "go test" based coverage workflow will continue to be supported, the proposal is to add coverage as a new build mode for "go build".

    In the same way that users can build a race-detector instrumented executable using "go build -race", it will be possible to build a coverage-instrumented executable using "go build -cover".

    Merging coverage profiles produced in different GOOS/GOARCH environments will be supported.


    Update March 2023, Go 1.20: "Code coverage for Go integration tests" shows that you can now build coverage-instrumented programs using “go build -cover”, then feed these instrumented binaries into an integration test to extend the scope of coverage testing.

    May 2024: Thom mentions in the comments:

    Additional info for blackbox testing: use flag coverpkg like this:

    go test -coverprofile=.coverage.html -coverpkg=your/pkg your/pkg/pkg_test