test-generation

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Test Generation

测试生成

Overview

概述

Generate comprehensive tests following TDD principles and project testing standards. Runs in isolated test-engineer context with pre-loaded testing conventions.
Announce at start: "I'm using the test-generation skill to create tests for [feature/component]."
遵循TDD原则和项目测试标准生成全面的测试。在预加载了测试约定的独立测试工程师环境中运行。
开始时需告知: "我正在使用测试生成技能为[功能/组件]创建测试。"

The Process

流程

Step 1: Specify Test Requirements

步骤1:明确测试需求

Provide clear requirements to test-engineer:
markdown
/test-generation

Feature: JWT token validation middleware

Behaviors:
1. Valid token → allow request
2. Expired token → reject with 401
3. Invalid signature → reject with 401
4. Missing token → reject with 401

Coverage: All critical paths

Testing Standards (pre-loaded):
- Framework: vitest
- Mocks: vi.mock()
- Structure: AAA pattern
向测试工程师提供清晰的需求:
markdown
/test-generation

Feature: JWT token validation middleware

Behaviors:
1. Valid token → allow request
2. Expired token → reject with 401
3. Invalid signature → reject with 401
4. Missing token → reject with 401

Coverage: All critical paths

Testing Standards (pre-loaded):
- Framework: vitest
- Mocks: vi.mock()
- Structure: AAA pattern

Step 2: Review Test Plan

步骤2:评审测试计划

Test-engineer proposes a test plan:
markdown
undefined
测试工程师会提出测试计划:
markdown
undefined

Test Plan

Test Plan

Behaviors:
  1. Valid token
    • ✅ Positive: Allow request with valid JWT
    • ❌ Negative: Reject malformed JWT
  2. Expired token
    • ✅ Positive: Normal token works
    • ❌ Negative: Expired token rejected with 401
Mocking Strategy:
  • JWT verification: Mock with vi.mock()
  • Request/Response: Use test doubles
Coverage Target: 95% line coverage, all critical paths

**IMPORTANT**: Review and approve before implementation proceeds.
Behaviors:
  1. Valid token
    • ✅ Positive: Allow request with valid JWT
    • ❌ Negative: Reject malformed JWT
  2. Expired token
    • ✅ Positive: Normal token works
    • ❌ Negative: Expired token rejected with 401
Mocking Strategy:
  • JWT verification: Mock with vi.mock()
  • Request/Response: Use test doubles
Coverage Target: 95% line coverage, all critical paths

**重要提示**:在开始实现前需评审并批准测试计划。

Step 3: Implement Tests

步骤3:实现测试

Test-engineer implements following AAA pattern (Arrange-Act-Assert):
typescript
describe('JWT Middleware', () => {
  it('allows request with valid token', () => {
    // Arrange
    const req = mockRequest({ headers: { authorization: 'Bearer valid.jwt.token' } });
    
    // Act
    const result = jwtMiddleware(req);
    
    // Assert
    expect(result.authorized).toBe(true);
  });
});
测试工程师遵循AAA模式(Arrange-Act-Assert)实现测试:
typescript
describe('JWT Middleware', () => {
  it('allows request with valid token', () => {
    // Arrange
    const req = mockRequest({ headers: { authorization: 'Bearer valid.jwt.token' } });
    
    // Act
    const result = jwtMiddleware(req);
    
    // Assert
    expect(result.authorized).toBe(true);
  });
});

Step 4: Run Self-Review

步骤4:执行自我评审

Test-engineer verifies:
  • ✅ Positive AND negative tests for each behavior
  • ✅ AAA pattern followed
  • ✅ All external dependencies mocked
  • ✅ Tests are deterministic (no flakiness)
  • ✅ Standards compliance
测试工程师需验证:
  • ✅ 每个行为都有正向和反向测试
  • ✅ 遵循AAA模式
  • ✅ 所有外部依赖均已Mock
  • ✅ 测试具有确定性(无不稳定情况)
  • ✅ 符合标准

Step 5: Run Tests

步骤5:运行测试

Execute test suite and verify all pass:
bash
npm test -- jwt.middleware.test.ts
执行测试套件并验证全部通过:
bash
npm test -- jwt.middleware.test.ts

Step 6: Return Results

步骤6:返回结果

yaml
status: success
tests_written: 8
coverage:
  lines: 96%
  branches: 93%
  functions: 100%
behaviors_tested:
  - name: "Valid token handling"
    positive_tests: 2
    negative_tests: 2
test_results:
  passed: 8
  failed: 0
deliverables:
  - "src/auth/jwt.middleware.test.ts"
yaml
status: success
tests_written: 8
coverage:
  lines: 96%
  branches: 93%
  functions: 100%
behaviors_tested:
  - name: "Valid token handling"
    positive_tests: 2
    negative_tests: 2
test_results:
  passed: 8
  failed: 0
deliverables:
  - "src/auth/jwt.middleware.test.ts"

TDD Workflow

TDD工作流

For test-driven development, invoke BEFORE implementation:
markdown
/test-generation

Write tests for user registration endpoint (not yet implemented):

Expected Behavior:
- POST /api/register with valid data → 201 + user object
- POST /api/register with duplicate email → 409 error
- POST /api/register with invalid email → 400 error

Note: Implementation does not exist. Write tests that define expected behavior.
Tests will fail initially—use them as spec to guide implementation.
对于测试驱动开发,需在实现前调用该技能:
markdown
/test-generation

Write tests for user registration endpoint (not yet implemented):

Expected Behavior:
- POST /api/register with valid data → 201 + user object
- POST /api/register with duplicate email → 409 error
- POST /api/register with invalid email → 400 error

Note: Implementation does not exist. Write tests that define expected behavior.
初始状态下测试会失败——可将这些测试作为规范来指导实现。

Error Handling

错误处理

Tests don't match project conventions:
  • Main agent must pre-load
    .opencode/context/core/standards/tests.md
Missing edge cases:
  • Specify explicitly in requirements
Flaky tests:
  • Ensure all external dependencies mocked
测试不符合项目约定:
  • 主代理必须预加载
    .opencode/context/core/standards/tests.md
缺少边缘案例:
  • 在需求中明确指定
不稳定测试:
  • 确保所有外部依赖均已Mock

Red Flags

警示信号

If you think any of these, STOP and re-read this skill:
  • "The implementation is simple enough that tests aren't needed"
  • "I'll just write the happy path tests for now"
  • "Mocking is too complex for this dependency"
  • "I'll add tests after the feature is stable"
如果出现以下任何想法,请停止操作并重新阅读本技能文档:
  • "这个实现足够简单,不需要测试"
  • "我先只写正常流程的测试"
  • "Mock这个依赖太复杂了"
  • "等功能稳定后再添加测试"

Common Rationalizations

常见借口与真相

ExcuseReality
"It's too simple to break"Simple code breaks in simple ways. Tests document the contract, not just catch bugs.
"Negative tests are obvious failures, not worth writing"Negative tests are where bugs hide. "Obviously fails" is not the same as "correctly fails".
"Mocking this dependency is too hard"Hard-to-mock dependencies are a design smell. Mock them anyway and note the smell.
"Tests slow down delivery"Tests without negative cases give false confidence. False confidence slows delivery more.
借口真相
"它太简单了,不会出问题"简单代码也会以简单的方式出错。测试记录的是契约,而不仅仅是捕获bug。
"反向测试明显会失败,不值得编写"反向测试是bug隐藏的地方。“明显会失败”和“正确地失败”不是一回事。
"Mock这个依赖太难了"难以Mock的依赖是设计缺陷。无论如何都要Mock,并记录该缺陷。
"测试会拖慢交付速度"没有反向测试的测试会给出错误的信心。错误的信心对交付速度的影响更大。

Remember

注意事项

  • Pre-load testing standards BEFORE invoking skill
  • Specify clear behaviors and acceptance criteria
  • Review test plan before implementation
  • Both positive AND negative tests required
  • All external dependencies MUST be mocked (no real network/DB calls)
  • AAA pattern (Arrange-Act-Assert) mandatory
  • Tests must be deterministic (no randomness or time dependencies)
  • 在调用技能前预加载测试标准
  • 指定清晰的行为和验收标准
  • 在实现前评审测试计划
  • 必须同时包含正向和反向测试
  • 所有外部依赖必须Mock(禁止真实的网络/数据库调用)
  • 必须遵循AAA模式(Arrange-Act-Assert)
  • 测试必须具有确定性(无随机性或时间依赖)

Related

相关技能

  • code-execution
  • code-review
  • context-discovery
  • code-execution
  • code-review
  • context-discovery