unit-testing - 当测试在另一个包中时获取覆盖率统计信息

标签 unit-testing go code-coverage

我的测试与我的代码不在同一个包中。我发现这是一种使用大量测试文件组织代码库的不那么困惑的方式,而且我读到这是一个好主意,可以将测试限制为通过包的公共(public) api 进行交互。

所以它看起来像这样:

api_client:
    Client.go
    ArtistService.go
    ...
api_client_tests
    ArtistService.Events_test.go
    ArtistService.Info_test.go
    UtilityFunction.go
    ...

我可以输入 go test bandsintown-api/api_client_tests -cover 并查看 0.181s 覆盖率:100.0% 的语句。但这实际上只是对我的 UtilityFunction.go 的覆盖(正如我在运行 go test bandsintown-api/api_client_tests -cover=cover.outgo tool cover -html=cover.out).

有没有什么方法可以覆盖被测的实际 api_client 包,而无需将它们全部放入同一个包中?

最佳答案

如评论中所述,您可以运行

go test -cover -coverpkg "api_client""api_client_tests"

以覆盖率运行测试。

但是将代码文件从测试文件拆分到不同的目录并不是 Go 的方式。

我想你想要进行黑盒测试(没有包私有(private)的东西可以在外面访问,即使是测试)。

为了完成这个,允许在另一个包中进行测试(不移动文件)。示例:

api_client.go

package api_client

// will not be accessible outside of the package
var privateVar = 10

func Method() {
}

api_client_test.go

package api_client_tests

import "testing"

func TestClient(t *testing.T) {
    Method()
}

关于unit-testing - 当测试在另一个包中时获取覆盖率统计信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37464156/

相关文章:

python - 用Python测试嵌入式系统的测试框架

go - golang中的var()是什么意思

go - Go 中的换行符 - 从 Go Tour 中理解这个例子

unit-testing - 在 GO 中测试 - 项目包中的代码覆盖率

java - 不同存储库中源代码和测试代码的代码覆盖率生成

unit-testing - 将依赖项注入(inject)到测试中

c# - DataTestMethods 的非编译时间常量

c# - 使用 Moq 模拟惰性界面

perl - 使用 Go 将文本文件从硬盘读取到内存的最快方法是什么?

c++ - 查找未执行的 C++ 代码行