乐于分享
好东西不私藏

AI 软件测试工程:Lesson 0009:测试覆盖率与 CI/CD 集成

AI 软件测试工程:Lesson 0009:测试覆盖率与 CI/CD 集成

第四部分:自动化测试 · Level 3 进阶

用 Codecov 监控测试质量,用 GitHub Actions 搭建自动回归流水线,让 TaskFlow 的每一行代码都有测试守护。


学习目标

为什么学习

Coverage 和 CI/CD 回答两个问题:"测了多少?" 和 "多久测一次?"

你将掌握:

  • 理解覆盖率的各种指标(行覆盖、函数覆盖、分支覆盖)
  • 掌握 Codecov 集成,监控覆盖率趋势
  • 搭建 GitHub Actions CI/CD 流水线
  • 设置质量门禁(Quality Gates)
  • 为 TaskFlow 搭建完整的 CI/CD 流程

实际价值

  • 每次 PR 都有自动测试 → 不用担心代码破坏
  • 覆盖率趋势可视化 → 看到测试质量的演变
  • 质量门禁 → 覆盖率不达标不能合并
  • 自动发布 → 代码通过测试后自动部署

一、什么是测试覆盖率?

💡 比喻 · 考试分数 vs 真才实学

覆盖率就像考试分数:

分数
含义
0-30%
交白卷(几乎没有测试)
50-70%
及格线(基本覆盖)
80-90%
良好(重点模块覆盖)
95%+
完美主义(100% 不代表没有 Bug)

但考 60 分不代表你真的学会了——测得多不代表测得对。

⚠️ 重要:覆盖率是工具,不是目标。100% 覆盖率的烂测试不如 70% 覆盖率的好测试。


二、覆盖率指标详解

四种覆盖率指标

指标
含义
参考目标
检测能力
行覆盖率
执行到的代码行数 / 总行数
≥ 80%
低(忽略分支)
函数覆盖率
被调用的函数数 / 总函数数
≥ 80%
分支覆盖率
if/else 的每个分支都跑到
≥ 70%
高(检测分支遗漏)
语句覆盖率
每个语句都执行到
≥ 80%

分支覆盖率示例

function getStatus(age) {if (age >= 18) {      // ✓ age >= 18 分支return 'adult'  } else {              // ❌ age < 18 分支(如果只测 age = 20)return 'minor'  }}// 分支覆盖率 = 50%(只覆盖了 if,没覆盖 else)

三、Codecov 集成

工作流程

开发者提交 PR       ↓GitHub Actions 运行测试       ↓生成 coverage/lcov.info       ↓上传到 Codecov       ↓Codecov 分析覆盖率       ↓返回覆盖率报告到 GitHub PR       ↓如果覆盖率下降 → PR 状态失败

GitHub Actions 配置

# .github/workflows/test.ymlname: Testson:push:branches: [maindevelop]pull_request:branches: [main]jobs:test:runs-on: ubuntu-lateststeps:uses: actions/checkout@v4uses: actions/setup-node@v4with:node-version: '20'cache: 'npm'run: npm cirun: npm run test:coverageuses: codecov/codecov-action@v4with:token: ${{ secrets.CODECOV_TOKEN }}fail_ci_if_error: true

Codecov 阈值配置

# codecov.ymlcoverage:precision: 2round: downrange: "70...100"status:project:default:target: 80%threshold: 1%patch:default:target: 80%

四、GitHub Actions CI/CD

TaskFlow CI/CD 流水线

┌─────────────────────────────────────────────────────┐│  TaskFlow CI/CD 流水线                              │├─────────────────────────────────────────────────────┤│                                                     ││  PR 提交                                            ││     ↓                                               ││  [1] 代码检查 (Lint + Type Check)                   ││     ↓                                               ││  [2] 单元测试 (Vitest)                             ││     ↓                                               ││  [3] 覆盖率检查 (Codecov)                           ││     ↓                                               ││  [4] 构建 (npm run build)                          ││     ↓                                               ││  [5] E2E 测试 (Playwright)                         ││     ↓                                               ││  [6] 部署预览 (Vercel Preview)                     ││                                                     │└─────────────────────────────────────────────────────┘

完整 CI 配置

# .github/workflows/ci.ymlname: CIon:push:branches: [maindevelop]pull_request:branches: [main]jobs:lint:runs-on: ubuntu-lateststeps:uses: actions/checkout@v4uses: actions/setup-node@v4with:node-version: '20'cache: 'npm'run: npm cirun: npm run lintrun: npm run typechecktest:runs-on: ubuntu-lateststeps:uses: actions/checkout@v4uses: actions/setup-node@v4with:node-version: '20'cache: 'npm'run: npm cirun: npm run test:runuses: codecov/codecov-action@v4with:token: ${{ secrets.CODECOV_TOKEN }}build:runs-on: ubuntu-latestneeds: [linttest]steps:uses: actions/checkout@v4uses: actions/setup-node@v4with:node-version: '20'cache: 'npm'run: npm cirun: npm run build

GitHub Actions 关键概念

概念
含义
workflow
一个 CI/CD 流程(一个 .yml 文件)
job
一个独立的工作(如 lint、test、build)
step
job 中的一个步骤
action
可复用的 action(如 actions/checkout@v4)
needs
依赖关系(job B needs job A)
secrets
加密的环境变量(API Token 等)

五、质量门禁(Quality Gates)

常见的质量门禁

门禁类型
工具
阈值示例
覆盖率
Codecov
总体 ≥ 80%,新增 ≥ 70%
代码风格
ESLint
0 errors
类型检查
TypeScript
0 errors
安全扫描
Snyk
0 vulnerabilities
测试通过率
Vitest
100%

设置 Branch Protection

GitHub → Settings → Branches → Add ruleBranch name pattern: mainRequired status checks:☑ Require a pull request before merging☑ Require status checks to pass before merging  - ci/Codecov (coverage/patch)  - ci/Codecov (coverage/project)☑ Require linear history☑ Do not allow bypassing the above settings

六、Vitest 覆盖率配置

// vitest.config.tsexport default defineConfig({test: {environment'jsdom',coverage: {provider'v8',reporter: ['text''json''html''lcov'],reportsDirectory'./coverage',include: ['src/**/*.{ts,tsx}'],exclude: ['src/**/*.d.ts','src/**/*.test.{ts,tsx}','src/test/**',      ],thresholds: {lines80,functions80,branches70,statements80,      },    },  },})

七、🤖 AI 实践

AI 实践 1:用 AI 生成 CI/CD 配置

Prompt 模板

请为以下项目生成 GitHub Actions CI/CD 配置。项目信息:- 框架:Next.js 14 + TypeScript- 测试:Vitest + Playwright- 部署:Vercel- 包管理:npm请生成:1. .github/workflows/ci.yml(包含 lint、test、coverage、build)2. codecov.yml(设置覆盖率阈值)

AI 实践 2:用 AI 分析覆盖率报告

Prompt 模板

请分析以下覆盖率报告,指出问题。```json{"total": {"lines": 85.5,"functions": 90.2,"branches": 62.3  }}

请分析:1. 分支覆盖率为什么这么低?2. 如何改进?

---## 八、✅ QA Checklist- [ ] 解释测试覆盖率的 4 种指标- [ ] 配置 Vitest 覆盖率报告- [ ] 注册 Codecov 并集成 GitHub- [ ] 配置 Codecov 覆盖率阈值- [ ] 创建 .github/workflows/ci.yml- [ ] 设置 GitHub Secrets- [ ] 设置 GitHub Branch Protection Rules- [ ] 理解 CI/CD 流水线的完整流程- [ ] 配置质量门禁(Quality Gates)- [ ] 用 AI 辅助生成 CI/CD 配置---## 九、❓ 思考题1. 覆盖率 100% 的测试就是"好测试"吗?你认为覆盖率指标中最重要的是哪一个?2. 分支覆盖率(70%)比行覆盖率(80%)低说明了什么?如何提高分支覆盖率?3. CI/CD 流水线中的"质量门禁"是否会让开发者变得"过度保守"?如何平衡质量和速度?4. 在 AI Coding 时代,AI 生成代码的覆盖率监控有什么特殊挑战?5. Codecov 显示覆盖率下降,但 PR 的代码确实写得没问题——这种情况下应该怎么办?---## 十、推荐阅读| 类型 | 资源 | 说明 ||------|------|------|| 文章 | [Vitest Coverage Guide](https://vitest.dev/guide/coverage.html) | Vitest 官方覆盖率文档 || 文章 | [Codecov Documentation](https://docs.codecov.com/) | Codecov 官方文档 || 文章 | [GitHub Actions](https://docs.github.com/en/actions) | GitHub Actions 完整参考 |---## 下一节预告**Lesson 0011:E2E 测试入门:Playwright 实战**- Playwright vs Cypress 对比- Playwright 安装与配置- 第一个 E2E 测试- 元素定位器(Selectors)- TaskFlow E2E 测试实战**前置知识**:Lesson 0010(CI/CD 集成)+ Lesson 0008(自动化测试基础)