实战

Claude Code 自动生成测试用例:单元测试、集成测试和 E2E 测试完整指南

Claude Code 自动生成测试用例完整指南:从函数签名生成边界条件测试、Table-Driven 测试模式、Mock 依赖注入、集成测试数据库 Fixtures、Playwright E2E 测试生成,以及提升测试覆盖率的系统化 Prompt 策略和 TDD 工作流。

2026/3/165分钟 阅读ClaudeEagle

写测试是提升代码质量最有效的方式,但也是最耗时的工作之一。 Claude Code 能从函数签名推断边界条件、生成完整的测试套件, 让测试覆盖率从 0 到 80% 变得简单很多。

核心 Prompt 策略

策略 1:提供实现,要求覆盖所有分支

Write comprehensive unit tests for this function: ```python def calculate_discount(price: float, user_type: str, coupon: str | None = None) -> float: if price <= 0: raise ValueError("Price must be positive") discount = 0.0 if user_type == "premium": discount = 0.2 elif user_type == "regular": discount = 0.1 if coupon == "EXTRA10": discount += 0.1 elif coupon == "HALF": discount = 0.5 return price * (1 - min(discount, 1.0))

Test requirements:

  1. Happy path for each user_type
  2. All coupon combinations
  3. Edge cases: price=0, negative price, unknown user_type
  4. Boundary: discount capped at 100% (coupon=HALF + premium)
  5. Type: use pytest + parametrize for similar cases

Use pytest, no external dependencies.

### 策略 2:Table-Driven 测试(适合多输入场景)

Write table-driven tests for the validate_email function. Use pytest.mark.parametrize.

Cover:

  • Valid emails (standard, subdomain, plus addressing)
  • Invalid: missing @, missing domain, double @, spaces
  • Edge cases: empty string, very long email (>254 chars)
  • Unicode: Chinese characters in local part

Format: @pytest.mark.parametrize("email,expected", [ ("valid@example.com", True), ... ]) def test_validate_email(email, expected): assert validate_email(email) == expected

### 策略 3:从行为描述生成测试(TDD 方式)

I'm going to implement a ShoppingCart class. Write tests FIRST based on this spec, before I write the code:

Spec:

  • Cart starts empty
  • add_item(product_id, quantity) adds items
  • Adding same product increases quantity
  • remove_item(product_id) removes item
  • get_total() returns sum of (price * quantity) for all items
  • apply_coupon("SAVE10") applies 10% discount to total
  • Cart cannot have negative quantities
  • Empty cart total is 0

Generate pytest tests that fully specify this behavior. I'll write the implementation to make them pass.

## 单元测试:Mock 依赖

Write unit tests for UserService.create_user() method.

The method:

  1. Validates email uniqueness (calls UserRepository.find_by_email)
  2. Hashes password (calls hash_password utility)
  3. Saves user (calls UserRepository.save)
  4. Sends welcome email (calls EmailService.send_welcome)
  5. Returns created user

Mock all external dependencies. Test cases:

  • Happy path: user created successfully
  • Email already exists: raises DuplicateEmailError
  • Repository save fails: raises exception, email NOT sent
  • Email send fails: user IS saved (email failure is non-critical)

Use pytest + unittest.mock (no pytest-mock). Show how to verify mock call arguments.

## 集成测试:数据库 Fixtures

Write pytest integration tests for OrderRepository.

Database: PostgreSQL (use pytest-asyncio + asyncpg for async)

Fixtures needed:

  1. test_db: create test database, run migrations, yield connection, cleanup
  2. clean_db: truncate all tables between tests (faster than recreate)
  3. sample_user: create a test user in DB
  4. sample_products: create 3 test products

Test cases:

  • create_order() inserts order + order_items correctly
  • get_order_by_id() returns full order with items
  • list_user_orders() returns correct pagination
  • update_order_status() updates and records history
  • concurrent creates don't deadlock

Use factory functions for test data, not hardcoded values.

## E2E 测试:Playwright

Write Playwright E2E tests for the checkout flow.

Flow: Login → Add to Cart → Checkout → Payment → Confirmation

Test file: tests/e2e/checkout.spec.ts

Setup:

  • Use Playwright with TypeScript
  • Base URL from environment variable
  • Use page fixtures with authenticated state (avoid login in every test)

Test cases:

  1. Complete checkout with valid card
  2. Form validation errors (empty fields)
  3. Payment failure (use Stripe test card 4000000000000002)
  4. Cart persists after page refresh
  5. Mobile viewport (375px) checkout works

Add custom page objects for:

  • CartPage (add item, view total)
  • CheckoutPage (fill form, submit)
  • ConfirmationPage (verify order number)

Include retry logic for flaky elements (waitForSelector with timeout).

## 提升覆盖率:分析未覆盖路径

Analyze the test coverage report and generate missing tests.

Current coverage: 67%

Uncovered lines from coverage report:

  • src/payment/processor.py lines 45-52 (refund edge case)
  • src/auth/middleware.py lines 88-95 (expired token path)
  • src/orders/service.py lines 120-135 (concurrent order creation)

For each uncovered section:

  1. Explain what scenario triggers this code path
  2. Write the minimum test to cover it
  3. Suggest if the code itself might have a bug

Coverage tool output: [粘贴 coverage report]

## TDD 工作流(测试先行) ```bash # 推荐的 Claude Code TDD 工作流 # Step 1: 描述需求,让 Claude 写测试 "Write tests for a rate limiter class that: - Allows N requests per minute per user - Returns True if allowed, False if blocked - Resets counter after 60 seconds" # Step 2: 运行测试(会失败,因为还没实现) pytest tests/test_rate_limiter.py # 确认测试是 FAIL 而不是 ERROR(测试本身没有语法错误) # Step 3: 让 Claude 实现代码 "Now implement RateLimiter to make these tests pass" # Step 4: 运行测试确认通过 pytest tests/test_rate_limiter.py -v # Step 5: 让 Claude 重构(测试保证不破坏功能) "Refactor RateLimiter to use Redis instead of in-memory dict. All tests must still pass."

CLAUDE.md 测试规范

markdown
## 测试规范

### 覆盖率目标
- 新代码:>85%
- 整体项目:>75%
- 核心业务逻辑:>95%

### 测试框架
- Python: pytest + pytest-asyncio
- TypeScript: Vitest + @testing-library
- E2E: Playwright

### 命名规范
- 测试函数:test_动词_场景_期望结果
  例:test_create_order_with_invalid_stock_raises_error
- 测试文件:与被测文件同名加 test_ 前缀

### 必须测试的内容
- 所有公共 API 方法
- 所有 if/else 分支
- 所有异常处理路径
- 边界值(0, -1, null, 空字符串, 超长输入)

来源:Anthropic 官方文档 + 测试工程最佳实践

相关文章推荐

实战Claude Code 测试覆盖率提升实战:从 30% 到 80% 的系统化方法用 Claude Code 系统性提升测试覆盖率的完整方法:快速识别覆盖率盲区(Istanbul/Coverage.py 报告解读)、让 Claude 针对未覆盖行生成测试的精准提示词、边界条件和异常路径的自动发现、集成测试 vs 单元测试的覆盖率策略、Mock 复杂依赖(数据库/HTTP/时间)的方法、测试质量 vs 测试数量的平衡、以及在 CI 中设置覆盖率门禁阻止质量退化。2026/3/21实战Claude Code 测试驱动开发(TDD)实战:AI 辅助红绿重构循环完全指南Claude Code 与测试驱动开发(TDD)深度结合实战:让 Claude 先写测试再写实现的完整工作流、Red-Green-Refactor 循环的 AI 辅助方式、测试用例描述转换为 Jest/pytest/Go test 测试代码、边界条件和异常路径的自动发现、用 Claude 做变异测试(Mutation Testing)发现测试盲区、提升测试质量的提示词技巧,以及 TDD 在遗留代码改造中的应用方法。2026/3/20实战用 AI 写单元测试:Claude Code 自动化测试生成完全指南Claude Code AI 自动化测试生成完全指南:为什么 AI 特别适合写测试、Jest/pytest/JUnit 三大框架使用示例、四大高价值测试场景(提升覆盖率/TDD/回归测试/批量补测试)、高质量测试 Prompt 写法、CLAUDE.md 固化测试规范与常见问题解答。2026/3/14实战Claude Code 命令行工具开发实战:用 AI 快速构建专业 CLI 工具Claude Code 辅助命令行工具(CLI)开发的完整实战指南:Python Click/Typer、Go Cobra、Rust Clap 技术栈选型、用 Claude Code 生成完整 CLI 项目结构(参数解析/子命令/全局选项)、交互式提示和彩色输出、配置文件管理、Shell 自动补全生成、跨平台打包(PyInstaller/goreleaser),以及发布到 PyPI/npm/Homebrew 的完整流程。2026/3/26实战Claude Code Vue 3 实战完全指南:Composition API 开发到企业级前端工程化Claude Code 辅助 Vue 3 开发的完整实战指南:Composition API 组件生成(setup/ref/computed)、Pinia 状态管理代码生成、Vue Router 4 路由配置、TypeScript 类型定义生成(Props/Emits)、Composables 抽象、Vitest 单元测试生成、性能优化(虚拟滚动/v-memo),以及 Options API 迁移和响应式丢失问题排查的 Prompt 模板。2026/3/26实战Claude Code Django 实战完全指南:从模型设计到 REST API 开发全流程Claude Code 辅助 Django 开发的完整实战指南:用 Claude Code 生成 Django 项目结构和 Models(含迁移文件)、Django REST Framework(DRF)API 开发(Serializer/ViewSet/Router)、用户认证系统(JWT/Session/第三方登录)、Django ORM 查询优化(select_related/prefetch_related/annotate)、异步任务(Celery + Redis)、测试用例生成(pytest-django)、Docker 化部署,以及在现有 Django 项目中快速定位和修复 Bug 的 Prompt 技巧。2026/3/26