unit-testing - 如何在 Go 中将所有包的代码覆盖率放在一起?

标签 unit-testing go code-coverage

我有一个包含多个包的库。运行测试时,我使用“-cover”标志并单独显示每个包的覆盖率信息。如下所示:

--- PASS: TestSampleTestSuite (0.00s)
PASS
coverage: 28.7% of statements
ok      github.com/path/to/package1 13.021s
?       github.com/path/to/package2 [no test files]

=== RUN   TestAbc
--- PASS: TestAbc (0.43s)
PASS
coverage: 27.7% of statements

有没有什么方法可以轻松获得完整的覆盖率概览,从而更好地了解整个项目的覆盖率?

更新:这是我正在使用的 go test 命令

go test ./... -v -short -p 1 -cover

最佳答案

编辑:自从我写下这个答案以来,情况发生了变化。请参阅 Go 1.10 的发行说明:https://golang.org/doc/go1.10#test :

The go test -coverpkg flag now interprets its argument as a comma-separated list of patterns to match against the dependencies of each test, not as a list of packages to load anew. For example, go test -coverpkg=all is now a meaningful way to run a test with coverage enabled for the test package and all its dependencies. Also, the go test -coverprofile option is now supported when running multiple tests.

你现在可以运行了

go test -v -coverpkg=./... -coverprofile=profile.cov ./...
go tool cover -func profile.cov

旧答案

这是从 https://github.com/h12w/gosweep 中提取的 bash 脚本:

#!/bin/bash
set -e

echo 'mode: count' > profile.cov

for dir in $(find . -maxdepth 10 -not -path './.git*' -not -path '*/_*' -type d);
do
if ls $dir/*.go &> /dev/null; then
    go test -short -covermode=count -coverprofile=$dir/profile.tmp $dir
    if [ -f $dir/profile.tmp ]
    then
        cat $dir/profile.tmp | tail -n +2 >> profile.cov
        rm $dir/profile.tmp
    fi
fi
done

go tool cover -func profile.cov

关于unit-testing - 如何在 Go 中将所有包的代码覆盖率放在一起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59354924/

相关文章:

laravel - 使用 TDD 构建 Laravel 应用程序 - 第 4 集,InvalidArgumentException : Unable to locate factory with name [default] [App\Project]

unit-testing - 未注入(inject)模拟对象

c++ - 可以将测试用例存储在相应的类中吗? (C++)

c# - 将构造函数参数传递给 Nunit 基类

inheritance - golang中如何设置继承

testing - 聚合来自不同测试框架的代码覆盖率

amazon-web-services - request.Body 通过 http 网关的值与通过测试 GUI 的值不同

reflection - 验证一个接口(interface)是否满足另一个接口(interface)

javascript - 如何使用新的 babel-plugin-__coverage__ 将覆盖率报告添加到 karma

visual-studio-2017 - 本地 Visual Studio 和 TFS 构建服务器中的代码覆盖率结果不匹配