测试覆盖率指南

覆盖率类型

类型度量内容局限性
行/语句覆盖哪些行被执行过未检查返回值、分支结果
分支覆盖每个条件的真/假两个分支比行覆盖好,但仍漏值组合
函数覆盖哪些函数被调用过最弱;不检查行为
变异测试测试能否捕获代码变化(缺陷)运行慢;是测试质量最好的指标

各语言覆盖率工具

# Go go test ./... -coverprofile=coverage.out go tool cover -html=coverage.out -o coverage.html go tool cover -func=coverage.out | grep total # 打印总覆盖率 # JavaScript(Vitest / Jest) npx vitest run --coverage npx jest --coverage # vitest.config.ts 覆盖率门限 export default { test: { coverage: { provider: 'v8', thresholds: { lines: 80, branches: 75, functions: 80, }, exclude: ['**/*.d.ts', '**/node_modules/**'], } } }; # Python(pytest-cov) pytest --cov=src --cov-report=html --cov-fail-under=80

覆盖率无法告诉你的事

100% 覆盖率不代表...示例
测试检查了正确的内容调用了函数但从未断言输出
所有边界情况都被覆盖边界条件的差一错误
集成能正常工作单元测试 Mock 了一切,真实 DB 行为可能不同
代码质量良好难以维护的代码上也能做到 100% 覆盖