SuperAPI AI 工具集

tdd

测试与质量

查看项目

更新于 10-15 15:40

技能介绍

用途

本技能是一套面向 AI 智能体与 LLM 的社区版测试驱动开发(TDD)最佳实践指南,用于指导测试编写、重构与代码生成。当需要以 TDD 工作流编写新测试、实践红-绿-重构循环、设计测试结构与组织、创建测试数据与夹具,或审查、重构现有测试套件时,可参考本指南。

TDD 工作流

  • RED:编写一个定义期望行为的失败测试。
  • GREEN:编写最少量代码使测试通过。
  • REFACTOR:在保持测试通过的前提下清理代码。
  • 针对每个新行为重复上述步骤。

规则类别与优先级

规则按影响力划分优先级,共 8 个类别、42 条规则:

优先级 类别 影响 前缀
1 Red-Green-Refactor Cycle CRITICAL cycle-
2 Test Design Principles CRITICAL design-
3 Test Isolation & Dependencies HIGH isolate-
4 Test Data Management HIGH data-
5 Assertions & Verification MEDIUM assert-
6 Test Organization & Structure MEDIUM org-
7 Test Performance & Reliability MEDIUM perf-
8 Test Pyramid & Strategy LOW strat-

快速参考

1. Red-Green-Refactor Cycle(CRITICAL)

  • cycle-write-test-first:先写测试再写实现
  • cycle-minimal-code-to-pass:只写足够让测试通过的代码
  • cycle-refactor-after-green:变绿后立即重构
  • cycle-verify-test-fails-first:写代码前先确认测试失败
  • cycle-small-increments:小步增量推进
  • cycle-maintain-test-list:维护测试清单

2. Test Design Principles(CRITICAL)

  • design-test-behavior-not-implementation:测试行为而非实现
  • design-one-assertion-per-test:每个测试一个逻辑断言
  • design-descriptive-test-names:使用描述性测试名称
  • design-aaa-pattern:遵循 Arrange-Act-Assert 模式
  • design-test-edge-cases:测试边界与边缘情况
  • design-avoid-logic-in-tests:避免在测试中包含逻辑

3. Test Isolation & Dependencies(HIGH)

  • isolate-mock-external-dependencies:模拟外部依赖
  • isolate-no-shared-state:避免测试间共享可变状态
  • isolate-deterministic-tests:编写确定性测试
  • isolate-prefer-stubs-over-mocks:查询优先使用 Stub 而非 Mock
  • isolate-use-dependency-injection:使用依赖注入提升可测试性

4. Test Data Management(HIGH)

  • data-use-factories:使用工厂创建测试数据
  • data-minimal-setup:保持测试设置最小化
  • data-avoid-mystery-guests:避免神秘访客(隐藏的外部数据依赖)
  • data-unique-identifiers:每个测试使用唯一标识符
  • data-builder-pattern:复杂对象使用构建器模式

5. Assertions & Verification(MEDIUM)

  • assert-specific-assertions:使用具体断言
  • assert-error-messages:对错误消息与类型进行断言
  • assert-no-assertions-antipattern:每个测试都必须有断言
  • assert-custom-matchers:为领域断言创建自定义匹配器
  • assert-snapshot-testing:谨慎使用快照测试

6. Test Organization & Structure(MEDIUM)

  • org-group-by-behavior:按行为而非方法分组测试
  • org-file-structure:遵循一致的测试文件结构
  • org-setup-teardown:恰当使用 Setup 与 Teardown 钩子
  • org-test-utilities:抽取可复用的测试工具
  • org-parameterized-tests:使用参数化测试处理变体

7. Test Performance & Reliability(MEDIUM)

  • perf-fast-unit-tests:保持单元测试足够快以支持持续反馈
  • perf-avoid-network-calls:在单元测试中消除网络调用
  • perf-fix-flaky-tests:立即修复易碎(不稳定)测试
  • perf-parallelize-tests:并行化相互独立的测试
  • perf-avoid-sleep:避免任意 Sleep 调用

8. Test Pyramid & Strategy(LOW)

  • strat-test-pyramid:遵循测试金字塔
  • strat-mutation-testing:使用变异测试验证测试质量
  • strat-coverage-targets:设置有意义的覆盖率目标
  • strat-integration-boundaries:在服务边界进行集成测试
  • strat-e2e-critical-paths:将 E2E 测试限制在关键用户路径

使用方式

对上述每条与任务匹配的规则,阅读 references/<rule-id>.md,了解其重要性以及错误与正确代码的对比示例。

相关技能

  • Vitest 框架细节参见 vitest 技能
  • 使用 MSW 进行 API 模拟参见 msw 技能

限制

资料未提供具体的安装命令、价格或平台支持等信息,暂未提供。