1. 创建Go模块和测试文件
创建目录
mkdir go_coverage_example
cd go_coverage_example
初始化Go模块
go mod init go_coverage_example
创建一个Go文件 main.go
package main
import "fmt"
func add(a, b int) int {
return a + b
}
func main() {
fmt.Println("Sum:", add(3, 4))
}
创建一个测试文件 main_test.go
package main
import "testing"
func TestAdd(t *testing.T) {
result := add(3, 4)
if result != 7 {
t.Errorf("Expected add(3, 4) to equal 7, but got %d", result)
}
}
2. 运行测试并收集覆盖率数据
运行测试并收集覆盖数据
go test -coverprofile=coverage.out
输出如下:
PASS
coverage: 50.0% of statements
ok go_coverage_example
3. 查看覆盖率报告
查看覆盖率的文本摘要
go tool cover -func=coverage.out
生成HTML覆盖率报告:
go tool cover -html=coverage.out -o coverage.html
打开生成的 coverage.html
文件,在浏览器中查看。绿色的行表示已经被测试覆盖的代码,红色的行表示未被覆盖的代码。go语言中测试代码覆盖率是通过插桩实现的,基本思想是在函数入口、循环、条件判断、返回语句等关键位置注入计数器代码。