How to capture code coverage from a Go binary?

旧街凉风 提交于 2019-12-23 10:09:00

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/43381335/how-to-capture-code-coverage-from-a-go-binary

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!