tdd-guide

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

TDD Guide - Test Driven Development for Engineering Teams

TDD指南 - 面向工程团队的测试驱动开发

A comprehensive Test Driven Development skill that provides intelligent test generation, coverage analysis, framework integration, and TDD workflow guidance across multiple languages and testing frameworks.
这是一项全面的测试驱动开发技能,可在多语言和多测试框架下提供智能测试生成、覆盖率分析、框架集成及TDD工作流指导。

Capabilities

核心功能

Test Generation

测试用例生成

  • Generate Test Cases from Requirements: Convert user stories, API specs, and business requirements into executable test cases
  • Create Test Stubs: Generate test function scaffolding with proper naming, imports, and setup/teardown
  • Generate Test Fixtures: Create realistic test data, mocks, and fixtures for various scenarios
  • 从需求生成测试用例:将用户故事、API规范和业务需求转换为可执行的测试用例
  • 生成测试桩代码:生成具备规范命名、导入语句及初始化/清理逻辑的测试函数脚手架
  • 生成测试夹具:为各类场景创建真实的测试数据、模拟对象及夹具

TDD Workflow Support

TDD工作流支持

  • Guide Red-Green-Refactor: Step-by-step guidance through TDD cycles with validation
  • Suggest Missing Scenarios: Identify untested edge cases, error conditions, and boundary scenarios
  • Review Test Quality: Analyze test isolation, assertions quality, naming conventions, and maintainability
  • 指导红-绿-重构流程:通过步骤化引导完成TDD周期并进行验证
  • 提示缺失场景:识别未被测试的边缘情况、错误条件及边界场景
  • 评审测试质量:分析测试隔离性、断言质量、命名规范及可维护性

Coverage & Metrics Analysis

覆盖率与指标分析

  • Calculate Coverage: Parse LCOV, JSON, and XML coverage reports for line/branch/function coverage
  • Identify Untested Paths: Find code paths, branches, and error handlers without test coverage
  • Recommend Improvements: Prioritized recommendations (P0/P1/P2) for coverage gaps and test quality
  • 计算覆盖率:解析LCOV、JSON和XML格式的覆盖率报告,获取行/分支/函数覆盖率数据
  • 识别未测试路径:找出无测试覆盖的代码路径、分支及错误处理逻辑
  • 提出改进建议:针对覆盖率缺口和测试质量提供优先级划分(P0/P1/P2)的改进建议

Framework Integration

框架集成

  • Multi-Framework Support: Jest, Pytest, JUnit, Vitest, Mocha, RSpec adapters
  • Generate Boilerplate: Create test files with proper imports, describe blocks, and best practices
  • Configure Test Runners: Set up test configuration, coverage tools, and CI integration
  • 多框架支持:适配Jest、Pytest、JUnit、Vitest、Mocha、RSpec等框架
  • 生成样板代码:创建具备正确导入、描述块及最佳实践的测试文件
  • 配置测试运行器:设置测试配置、覆盖率工具及CI集成

Comprehensive Metrics

全面指标分析

  • Test Coverage: Line, branch, function coverage with gap analysis
  • Code Complexity: Cyclomatic complexity, cognitive complexity, testability scoring
  • Test Quality: Assertions per test, isolation score, naming quality, test smell detection
  • Test Data: Boundary value analysis, edge case identification, mock data generation
  • Test Execution: Timing analysis, slow test detection, flakiness detection
  • Missing Tests: Uncovered edge cases, error handling gaps, missing integration scenarios
  • 测试覆盖率:行、分支、函数覆盖率及缺口分析
  • 代码复杂度:圈复杂度、认知复杂度、可测试性评分
  • 测试质量:单测试断言数、隔离性评分、命名质量、测试坏味检测
  • 测试数据:边界值分析、边缘场景识别、模拟数据生成
  • 测试执行:耗时分析、慢测试检测、不稳定测试检测
  • 缺失测试:未覆盖的边缘场景、错误处理缺口、缺失的集成场景

Input Requirements

输入要求

The skill supports automatic format detection for flexible input:
该技能支持自动格式检测,输入方式灵活:

Source Code

源代码

  • Languages: TypeScript, JavaScript, Python, Java
  • Format: Direct file paths or copy-pasted code blocks
  • Detection: Automatic language/framework detection from syntax and imports
  • 支持语言:TypeScript、JavaScript、Python、Java
  • 格式:直接提供文件路径或粘贴代码块
  • 检测:通过语法和导入语句自动检测语言/框架

Test Artifacts

测试工件

  • Coverage Reports: LCOV (.lcov), JSON (coverage-final.json), XML (cobertura.xml)
  • Test Results: JUnit XML, Jest JSON, Pytest JSON, TAP format
  • Format: File paths or raw coverage data
  • 覆盖率报告:LCOV(.lcov)、JSON(coverage-final.json)、XML(cobertura.xml)
  • 测试结果:JUnit XML、Jest JSON、Pytest JSON、TAP格式
  • 格式:文件路径或原始覆盖率数据

Requirements (Optional)

需求(可选)

  • User Stories: Text descriptions of functionality
  • API Specifications: OpenAPI/Swagger, REST endpoints, GraphQL schemas
  • Business Requirements: Acceptance criteria, business rules
  • 用户故事:功能的文本描述
  • API规范:OpenAPI/Swagger、REST端点、GraphQL模式
  • 业务需求:验收标准、业务规则

Input Methods

输入方式

  • Option A: Provide file paths (skill will read files)
  • Option B: Copy-paste code/data directly
  • Option C: Mix of both (automatically detected)
  • 选项A:提供文件路径(技能将读取文件)
  • 选项B:直接粘贴代码/数据
  • 选项C:混合使用(自动检测)

Output Formats

输出格式

The skill provides context-aware output optimized for your environment:
该技能提供上下文感知的输出,针对不同环境优化:

Code Files

代码文件

  • Test Files: Generated tests (Jest/Pytest/JUnit/Vitest) with proper structure
  • Fixtures: Test data files, mock objects, factory functions
  • Mocks: Mock implementations, stub functions, test doubles
  • 测试文件:生成符合Jest/Pytest/JUnit/Vitest规范的测试文件
  • 夹具:测试数据文件、模拟对象、工厂函数
  • 模拟实现:Mock实现、桩函数、测试替身

Reports

报告

  • Markdown: Rich coverage reports, recommendations, quality analysis (Claude Desktop)
  • JSON: Machine-readable metrics, structured data for CI/CD integration
  • Terminal-Friendly: Simplified output for Claude Code CLI
  • Markdown:丰富的覆盖率报告、改进建议、质量分析(适用于Claude桌面端)
  • JSON:机器可读的指标数据,适用于CI/CD集成
  • 终端友好格式:精简输出,适用于Claude Code CLI

Smart Defaults

智能默认值

  • Desktop/Apps: Rich markdown with tables, code blocks, visual hierarchy
  • CLI: Concise, terminal-friendly format with clear sections
  • CI/CD: JSON output for automated processing
  • 桌面/应用端:带表格、代码块、视觉层级的丰富Markdown格式
  • CLI:简洁、终端友好的分段格式
  • CI/CD:JSON格式输出,便于自动化处理

Progressive Disclosure

渐进式披露

  • Summary First: High-level overview (<200 tokens)
  • Details on Demand: Full analysis available (500-1000 tokens)
  • Prioritized: P0 (critical) → P1 (important) → P2 (nice-to-have)
  • 先看摘要:高层级概述(少于200词)
  • 按需查看详情:完整分析内容(500-1000词)
  • 优先级划分:P0(关键)→ P1(重要)→ P2(锦上添花)

How to Use

使用方法

Basic Usage

基础用法

@tdd-guide

I need tests for my authentication module. Here's the code:
[paste code or provide file path]

Generate comprehensive test cases covering happy path, error cases, and edge cases.
@tdd-guide

我需要为我的认证模块生成测试。以下是代码:
[粘贴代码或提供文件路径]

生成覆盖正常流程、错误场景及边缘情况的全面测试用例。

Coverage Analysis

覆盖率分析

@tdd-guide

Analyze test coverage for my TypeScript project. Coverage report: coverage/lcov.info

Identify gaps and provide prioritized recommendations.
@tdd-guide

分析我的TypeScript项目的测试覆盖率。覆盖率报告路径:coverage/lcov.info

识别覆盖率缺口并提供优先级划分的改进建议。

TDD Workflow

TDD工作流

@tdd-guide

Guide me through TDD for implementing a password validation function.

Requirements:
- Min 8 characters
- At least 1 uppercase, 1 lowercase, 1 number, 1 special char
- No common passwords
@tdd-guide

指导我通过TDD流程实现密码验证函数。

需求:
- 至少8个字符
- 包含至少1个大写字母、1个小写字母、1个数字、1个特殊字符
- 不能是常见密码

Multi-Framework Support

多框架支持

@tdd-guide

Convert these Jest tests to Pytest format:
[paste Jest tests]
@tdd-guide

将这些Jest测试转换为Pytest格式:
[粘贴Jest测试代码]

Scripts

核心脚本

Core Modules

核心模块

  • test_generator.py: Intelligent test case generation from requirements and code
  • coverage_analyzer.py: Parse and analyze coverage reports (LCOV, JSON, XML)
  • metrics_calculator.py: Calculate comprehensive test and code quality metrics
  • framework_adapter.py: Multi-framework adapter (Jest, Pytest, JUnit, Vitest)
  • tdd_workflow.py: Red-green-refactor workflow guidance and validation
  • fixture_generator.py: Generate realistic test data and fixtures
  • format_detector.py: Automatic language and framework detection
  • test_generator.py:从需求和代码智能生成测试用例
  • coverage_analyzer.py:解析并分析覆盖率报告(LCOV、JSON、XML)
  • metrics_calculator.py:计算全面的测试及代码质量指标
  • framework_adapter.py:多框架适配器(Jest、Pytest、JUnit、Vitest)
  • tdd_workflow.py:红-绿-重构工作流引导与验证
  • fixture_generator.py:生成真实的测试数据及夹具
  • format_detector.py:自动检测语言与框架

Utilities

工具类

  • complexity_analyzer.py: Cyclomatic and cognitive complexity analysis
  • test_quality_scorer.py: Test quality scoring (isolation, assertions, naming)
  • missing_test_detector.py: Identify untested paths and missing scenarios
  • output_formatter.py: Context-aware output formatting (Desktop vs CLI)
  • complexity_analyzer.py:圈复杂度与认知复杂度分析
  • test_quality_scorer.py:测试质量评分(隔离性、断言、命名)
  • missing_test_detector.py:识别未测试路径与缺失场景
  • output_formatter.py:上下文感知的输出格式化(桌面端 vs CLI)

Best Practices

最佳实践

Test Generation

测试用例生成

  1. Start with Requirements: Write tests from user stories before seeing implementation
  2. Test Behavior, Not Implementation: Focus on what code does, not how it does it
  3. One Assertion Focus: Each test should verify one specific behavior
  4. Descriptive Names: Test names should read like specifications
  1. 从需求出发:在查看实现代码前,先根据用户故事编写测试
  2. 测试行为而非实现:关注代码的功能,而非实现方式
  3. 单一断言聚焦:每个测试应仅验证一个特定行为
  4. 描述性命名:测试名称应像规格说明一样清晰可读

TDD Workflow

TDD工作流

  1. Red: Write failing test first
  2. Green: Write minimal code to make it pass
  3. Refactor: Improve code while keeping tests green
  4. Repeat: Small iterations, frequent commits
  1. :先编写失败的测试
  2. 绿:编写最少的代码使测试通过
  3. 重构:在保持测试通过的同时优化代码
  4. 重复:小迭代,频繁提交

Coverage Goals

覆盖率目标

  1. Aim for 80%+: Line coverage baseline for most projects
  2. 100% Critical Paths: Authentication, payments, data validation must be fully covered
  3. Branch Coverage Matters: Line coverage alone is insufficient
  4. Don't Game Metrics: Focus on meaningful tests, not coverage numbers
  1. 目标80%+:大多数项目的行覆盖率基准
  2. 关键路径100%覆盖:认证、支付、数据验证等模块必须完全覆盖
  3. 分支覆盖率很重要:仅行覆盖率是不够的
  4. 不要为指标而指标:关注有意义的测试,而非覆盖率数字

Test Quality

测试质量

  1. Independent Tests: Each test should run in isolation
  2. Fast Execution: Keep unit tests under 100ms each
  3. Deterministic: Tests should always produce same results
  4. Clear Failures: Assertion messages should explain what went wrong
  1. 独立测试:每个测试应能独立运行
  2. 快速执行:单元测试应控制在100毫秒以内
  3. 确定性:测试应始终产生相同的结果
  4. 清晰的失败信息:断言消息应明确说明问题所在

Framework Selection

框架选择

  1. Jest: JavaScript/TypeScript projects (React, Node.js)
  2. Pytest: Python projects (Django, Flask, FastAPI)
  3. JUnit: Java projects (Spring, Android)
  4. Vitest: Modern Vite-based projects
  1. Jest:适用于JavaScript/TypeScript项目(React、Node.js)
  2. Pytest:适用于Python项目(Django、Flask、FastAPI)
  3. JUnit:适用于Java项目(Spring、Android)
  4. Vitest:适用于现代Vite生态项目

Multi-Language Support

多语言支持

TypeScript/JavaScript

TypeScript/JavaScript

  • Frameworks: Jest, Vitest, Mocha, Jasmine
  • Runners: Node.js, Karma, Playwright
  • Coverage: Istanbul/nyc, c8
  • 框架:Jest、Vitest、Mocha、Jasmine
  • 运行器:Node.js、Karma、Playwright
  • 覆盖率工具:Istanbul/nyc、c8

Python

Python

  • Frameworks: Pytest, unittest, nose2
  • Runners: pytest, tox, nox
  • Coverage: coverage.py, pytest-cov
  • 框架:Pytest、unittest、nose2
  • 运行器:pytest、tox、nox
  • 覆盖率工具:coverage.py、pytest-cov

Java

Java

  • Frameworks: JUnit 5, TestNG, Mockito
  • Runners: Maven Surefire, Gradle Test
  • Coverage: JaCoCo, Cobertura
  • 框架:JUnit 5、TestNG、Mockito
  • 运行器:Maven Surefire、Gradle Test
  • 覆盖率工具:JaCoCo、Cobertura

Limitations

局限性

Scope

范围限制

  • Unit Tests Focus: Primarily optimized for unit tests (integration tests require different patterns)
  • Static Analysis Only: Cannot execute tests or measure actual code behavior
  • Language Support: Best support for TypeScript, JavaScript, Python, Java (other languages limited)
  • 聚焦单元测试:主要针对单元测试优化(集成测试需要不同的模式)
  • 仅静态分析:无法执行测试或测量实际代码行为
  • 语言支持:对TypeScript、JavaScript、Python、Java支持最佳(其他语言支持有限)

Coverage Analysis

覆盖率分析

  • Report Dependency: Requires existing coverage reports (cannot generate coverage from scratch)
  • Format Support: LCOV, JSON, XML only (other formats need conversion)
  • Interpretation Context: Coverage numbers need human judgment for meaningfulness
  • 依赖现有报告:需要已有的覆盖率报告(无法从零生成覆盖率数据)
  • 格式支持有限:仅支持LCOV、JSON、XML格式(其他格式需转换)
  • 需人工解读:覆盖率数字需要结合人工判断才有实际意义

Test Generation

测试生成

  • Baseline Quality: Generated tests provide scaffolding, require human review and refinement
  • Complex Logic: Advanced business logic and integration scenarios need manual test design
  • Mocking Strategy: Mock/stub strategies should align with project patterns
  • 基础质量保障:生成的测试仅提供脚手架,需要人工审核和完善
  • 复杂逻辑限制:高级业务逻辑和集成场景需要手动设计测试
  • 模拟策略对齐:模拟/桩函数策略需与项目现有模式保持一致

Framework Integration

框架集成

  • Configuration Required: Test runners need proper setup (this skill doesn't modify package.json or pom.xml)
  • Version Compatibility: Generated code targets recent stable versions (Jest 29+, Pytest 7+, JUnit 5+)
  • 需自行配置:测试运行器需要正确设置(本技能不会修改package.json或pom.xml)
  • 版本兼容性:生成的代码适配最新稳定版本(Jest 29+、Pytest 7+、JUnit 5+)

When NOT to Use This Skill

不适用场景

  • E2E Testing: Use dedicated E2E tools (Playwright, Cypress, Selenium)
  • Performance Testing: Use JMeter, k6, or Locust
  • Security Testing: Use OWASP ZAP, Burp Suite, or security-focused tools
  • Manual Testing: Some scenarios require human exploratory testing
  • 端到端测试:使用专用的E2E工具(Playwright、Cypress、Selenium)
  • 性能测试:使用JMeter、k6或Locust
  • 安全测试:使用OWASP ZAP、Burp Suite或专注安全的工具
  • 手动测试:部分场景需要人工探索性测试

Example Workflows

示例工作流

Workflow 1: Generate Tests from Requirements

工作流1:从需求生成测试

Input: User story + API specification
Process: Parse requirements → Generate test cases → Create test stubs
Output: Complete test files ready for implementation
输入:用户故事 + API规范
流程:解析需求 → 生成测试用例 → 创建测试桩代码
输出:可直接用于实现的完整测试文件

Workflow 2: Improve Coverage

工作流2:提升覆盖率

Input: Coverage report + source code
Process: Identify gaps → Suggest tests → Generate test code
Output: Prioritized test cases for uncovered code
输入:覆盖率报告 + 源代码
流程:识别缺口 → 建议测试用例 → 生成测试代码
输出:针对未覆盖代码的优先级测试用例

Workflow 3: TDD New Feature

工作流3:TDD开发新功能

Input: Feature requirements
Process: Guide red-green-refactor → Validate each step → Suggest refactorings
Output: Well-tested feature with clean code
输入:功能需求
流程:引导红-绿-重构 → 验证每一步 → 提出重构建议
输出:测试完善、代码简洁的功能模块

Workflow 4: Framework Migration

工作流4:框架迁移

Input: Tests in Framework A
Process: Parse tests → Translate patterns → Generate equivalent tests
Output: Tests in Framework B with same coverage
输入:框架A中的测试代码
流程:解析测试 → 转换模式 → 生成等效测试
输出:框架B中的测试代码,保持相同覆盖率

Integration Points

集成场景

CI/CD Integration

CI/CD集成

  • Parse coverage reports from CI artifacts
  • Generate coverage badges and reports
  • Fail builds on coverage thresholds
  • Track coverage trends over time
  • 从CI工件中解析覆盖率报告
  • 生成覆盖率徽章和报告
  • 当覆盖率低于阈值时触发构建失败
  • 跟踪覆盖率随时间的变化趋势

IDE Integration

IDE集成

  • Generate tests for selected code
  • Run coverage analysis on save
  • Highlight untested code paths
  • Quick-fix suggestions for test gaps
  • 为选中的代码生成测试
  • 保存时自动运行覆盖率分析
  • 高亮未测试的代码路径
  • 针对测试缺口提供快速修复建议

Code Review

代码评审

  • Validate test coverage in PRs
  • Check test quality standards
  • Identify missing test scenarios
  • Suggest improvements before merge
  • 在PR中验证测试覆盖率
  • 检查测试质量标准
  • 识别缺失的测试场景
  • 合并前提出改进建议

Version Support

版本支持

  • Node.js: 16+ (Jest 29+, Vitest 0.34+)
  • Python: 3.8+ (Pytest 7+)
  • Java: 11+ (JUnit 5.9+)
  • TypeScript: 4.5+
  • Node.js:16+(适配Jest 29+、Vitest 0.34+)
  • Python:3.8+(适配Pytest 7+)
  • Java:11+(适配JUnit 5.9+)
  • TypeScript:4.5+

Related Skills

相关技能

This skill works well with:
  • code-review: Validate test quality during reviews
  • refactoring-assistant: Maintain tests during refactoring
  • ci-cd-helper: Integrate coverage in pipelines
  • documentation-generator: Generate test documentation
本技能与以下技能配合使用效果更佳:
  • code-review:评审过程中验证测试质量
  • refactoring-assistant:重构过程中维护测试
  • ci-cd-helper:在流水线中集成覆盖率分析
  • documentation-generator:生成测试文档