【发布时间】:2019-09-18 10:22:30
【问题描述】:
我想获得用 Go 编写的 REST 服务的测试覆盖率。我通过 goroutine 生成 REST 服务,然后使用 REST 客户端发出 HTTP 请求,并查看 HTTP 响应。
测试成功通过,但 go test -cover 返回 0% 的测试覆盖率。
有没有办法获得 go lang REST 服务中使用的所有包的实际测试覆盖率。
我的测试文件: main_test.go
import (
"testing"
)
// Test started when the test binary is started. Only calls main.
func TestSystem(t *testing.T) {
go main() // Spinning up the go lang REST server in a separate go routine.
http.Post("https://localhost/do_something")
}
我的输出:
go test -cover main_test.go
ok command-line-arguments 0.668s coverage: 0.0% of statements
【问题讨论】:
-
你启动了你的服务并向它发出了请求,但你甚至没有给一毫秒来处理这个请求。如果在
http.Post之后添加time.Sleep(time.Second)会变成什么?尽管我建议您考虑将测试组织成套件:a) 使用go main()启动,b) 测试本身,c) 如果需要则拆除 -
我怀疑问题在于您正在计算错误包的统计信息。使用
-coverpkg标志来指示要为哪些包计算覆盖率统计信息。见here。 -
另外,正如下面的 cmets 中所述,您调用 goroutine 的方式是完全错误的。您可能不应该在 goroutine 中运行
main()。相反,启动一个 goroutine 来启动您的应用程序,但可以在测试完成后取消,可能使用context.Context。 -
这不是单元测试......它不是。老实说,运行所有内容并发出请求与
go run . &; curl 0.0.0.0:8080/do_something之类的 bash 脚本相同 -
为什么你忽略了
http.Post的响应和错误检查?至少您需要添加resp, err:= http.Post("https://localhost/do_something")并在之后检查resp and err。也许您正在尝试在不存在的网址上发布?
标签: go code-coverage