How to capture code coverage from a Go binary?

huangapple go评论101阅读模式
英文:

How to capture code coverage from a Go binary?

问题

我知道在运行单元测试时可以捕获代码覆盖率指标。然而,我们想知道当我们对二进制文件本身运行集成测试(复数形式)时的覆盖率是多少,例如:

go build
./mybin somefile1
./mybin somefile2
# ... 测试更多的文件和输入标志

这个是否可能?二进制文件可以专门为测试目的构建,因此可以根据需要进行编译选项。

英文:

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

得分: 7

Go覆盖率工具只能与testing包一起使用。但并非一切都无望。

如果你能将集成测试强制转换为Go测试框架,那么你应该拥有所需的一切。这并不像听起来那么困难。

基本上:

  1. 编写一个测试文件,在其中使用go routine执行你的main()函数:

     func TestMainApp(t *testing.T) {
         go main()
         // .. 然后开始你的集成测试
     }
    
  2. 在测试中运行你的真实应用程序,可能需要使用exec.Cmd来帮助启动集成测试。

  3. 收集你的覆盖率统计信息。

  4. 获得收益。

这篇一年前的文章Go coverage with external tests概述了类似的方法。

英文:

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.

huangapple
  • 本文由 发表于 2017年4月13日 07:43:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/43381335.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定