英文:
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测试框架,那么你应该拥有所需的一切。这并不像听起来那么困难。
基本上:
-
编写一个测试文件,在其中使用go routine执行你的
main()
函数:func TestMainApp(t *testing.T) { go main() // .. 然后开始你的集成测试 }
-
在测试中运行你的真实应用程序,可能需要使用exec.Cmd来帮助启动集成测试。
-
收集你的覆盖率统计信息。
-
获得收益。
这篇一年前的文章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:
-
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 }
-
With your real app running from within a test, start your integration tests--likely with the help of exec.Cmd.
-
Gather your coverage stats.
-
Profit.
This article, Go coverage with external tests, from a year ago, outlines a similar approach.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论