一、问题描述:
使用golang开发项目的时候,需要对设计的功能进行测试,这时候就需要编写测试用例进行测试,为了对项目整体的测试用例有个整体把握,测试报告就必不可少了。
二、golang项目的测试用例编写规则
1、在Go中,测试代码通常与被测试的代码放在同一个包下,并且以_test.go为后缀,例如:add_test.go;
2、测试用例的函数名要以Test开头,例如:
func TestAdd(t *testing.T) {
result := Add(1, 2)
if result != 3 {
t.Errorf("Add(1, 2) = %d; want 3", result)
}
三、测试用例的运行
1、测试用例的运行:go test filename_test.go
2、指定某个测试函数运行:go test -run TestFunctionName
3、生成覆盖率:
- 首先执行:
go test -v -covermode=count -coverprofile=cover.out - 最后执行:
go tool cover -html=cover.out -o cover.html - 这时候生成的覆盖率文件内容是:

四、生成整个项目的测试报告及覆盖率
1、在main.go的同级目录执行命令:go test -covermode=count -coverprofile=coverprofile.cov -gcflags "all=-N -l" -run="^Test" -coverpkg=$(go list ./... | grep -v "/test" | tr '\n' ',') ./...
2、测试报告的生成需要依赖外部包,其步骤如下:
- 首先下载该包:
go get -u github.com/vakenbolt/go-test-report/ - 执行测试报告生成命令:
go test -v -json | go run github.com/vakenbolt/go-test-report - 输出结果如下图所示:

详细的项目信息可以查看:https://gitcode.com/gh_mirrors/go/go-test-report

2404

被折叠的 条评论
为什么被折叠?



