7

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.

2
  • 1
    Is it an option to execute your tests using the go test framework? Commented Apr 13, 2017 at 0:21
  • That is possible. I could just effectively stub the os.Args and call it from a test. However, I'd prefer a black box approach where I can see what areas of the application are not touched when run through the CLI. Also the bash might get way more complicated and change a lot in time. It's easier to manage like this than through Go. Commented Apr 13, 2017 at 0:32

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Starting with Go 1.20 (Feb 2023), a program can be built to produce coverage data,
with the -coveroption.

From https://go.dev/doc/build-cover :

To build an application for collecting coverage profiles, pass the -cover flag when invoking go build on your application binary target. See the section below for a sample go build -cover invocation. The resulting binary can then be run using an environment variable setting to capture coverage profiles

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.