Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture code coverage from a Go binary?

I know its possible to capture code coverage metrics when running unit tests. However, we would like to know what the coverage is when we run integrations tests (plural) against the binary itself, like:

go build
./mybin somefile1
./mybin somefile2
# ... test a bunch more files and input flags

Is it possible to do this? The binary can be built just for the purpose of testing, so any compile options as needed.

like image 781
Elliot Chance Avatar asked Apr 12 '17 23:04

Elliot Chance


1 Answers

The Go coverage tool only works in conjunction with the testing package. But not all hope is lost.

If you can coerce your integration tests into the go testing framework, you should have all you need. This shouldn't be as hard as it sounds.

Basically:

  1. Write a test file that executes your main() function in a go routine:

    func TestMainApp(t *testing.T) {
        go main()
        // .. then start your integration tests
    }
    
  2. With your real app running from within a test, start your integration tests--likely with the help of exec.Cmd.

  3. Gather your coverage stats.

  4. Profit.

This article, Go coverage with external tests, from a year ago, outlines a similar approach.

like image 189
Flimzy Avatar answered Sep 30 '22 22:09

Flimzy