Go coverage for external tests with Cobra

Prerequisite reading: Go coverage with external tests

Go coverage can be generated by a CLI tool by compiling it as a test binary and passing it the test coverage flags. There's one catch: coverage will not be generated if the program does not exit with status 0, so its not possible to get coverage for tests of failure cases.

Instructions for generating coverage in this way are described in Go coverage with external tests and won't be repeated here.

However, if you're using Cobra you need to bind the test flags to pflag to be able to parse them. During program setup (before calling cobra.Command.Execute), execute the following:


And when running the compiled test binary, use --test.coverprofile instead of -test.coverprofile:

go test -coverpkg="../../pkg" -c -tags testrunmain mycmd
./mycmd.test --arg1=foo --arg2=bar --test.coverprofile=system.out

If you're using urfave/cli, I wasn't able to find any way to get the test coverage flags to parse without conflicting with the binary's flags.