by alirezarezvani
在代码之后编写测试会导致覆盖不完整和技术债务。本技能通过智能测试生成和覆盖分析,指导您完成红-绿-重构循环,强制执行TDD规范。
1. 打开 Claude 聊天界面
2. 点击下方 "📋 复制" 按钮
3. 粘贴到 Claude 聊天框中并发送
4. 输入 "使用 tdd-guide 技能" 开始使用
=== tdd-guide 技能 === 作者: alirezarezvani 描述: 在代码之后编写测试会导致覆盖不完整和技术债务。本技能通过智能测试生成和覆盖分析,指导您完成红-绿-重构循环,强制执行TDD规范。 使用方法: 1. 调用技能: "使用 tdd-guide 技能" 2. 提供相关信息: 根据技能要求提供必要参数 3. 查看结果: 技能会返回处理结果 示例: "使用 tdd-guide 技能,帮我分析一下这段代码"
这种方法适用于所有 Claude 用户,不需要安装额外工具。
coding
safe
Version: 1.0.0 Last Updated: November 5, 2025 Author: Claude Skills Factory
A comprehensive Test Driven Development skill for Claude Code that provides intelligent test generation, coverage analysis, framework integration, and TDD workflow guidance across multiple languages and testing frameworks.
The TDD Guide skill transforms how engineering teams implement Test Driven Development by providing:
Download the skill folder:
# Option A: Clone from repository
git clone https://github.com/your-org/tdd-guide-skill.git
# Option B: Download ZIP and extract
Install to Claude skills directory:
# Project-level (recommended for team projects)
cp -r tdd-guide /path/to/your/project/.claude/skills/
# User-level (available for all projects)
cp -r tdd-guide ~/.claude/skills/
Verify installation:
ls ~/.claude/skills/tdd-guide/
# Should show: SKILL.md, *.py files, samples
skill-creator skill to import the ZIP file# Upload skill via API
import anthropic
client = anthropic.Anthropic(api_key="your-api-key")
# Create skill with files
skill = client.skills.create(
name="tdd-guide",
files=["tdd-guide/SKILL.md", "tdd-guide/*.py"]
)
@tdd-guide
Generate tests for password validation function:
- Min 8 characters
- At least 1 uppercase, 1 lowercase, 1 number, 1 special char
Language: TypeScript
Framework: Jest
@tdd-guide
Analyze coverage from: coverage/lcov.info
Target: 80% coverage
Prioritize recommendations
@tdd-guide
Guide me through TDD for implementing user authentication.
Requirements: Email/password login, session management
Framework: Pytest
The skill includes 8 Python modules organized by functionality:
test_generator.py (450 lines)
coverage_analyzer.py (380 lines)
metrics_calculator.py (420 lines)
framework_adapter.py (480 lines)
tdd_workflow.py (380 lines)
fixture_generator.py (340 lines)
format_detector.py (280 lines)
Input:
@tdd-guide
User Story: As a user, I want to add items to my shopping cart
Acceptance Criteria:
- Add single item with quantity
- Update quantity if item already exists
- Validate quantity is positive
- Return updated cart total
Language: Python
Framework: Pytest
Output:
import pytest
from shopping_cart import ShoppingCart
class TestShoppingCart:
"""Test suite for shopping cart functionality."""
def test_add_single_item_successfully(self):
"""Should add single item with quantity."""
cart = ShoppingCart()
cart.add_item('apple', quantity=3, price=1.50)
assert len(cart.items) == 1
assert cart.items['apple']['quantity'] == 3
assert cart.get_total() == 4.50
def test_update_quantity_for_existing_item(self):
"""Should update quantity if item already exists."""
cart = ShoppingCart()
cart.add_item('apple', quantity=3, price=1.50)
cart.add_item('apple', quantity=2, price=1.50)
assert cart.items['apple']['quantity'] == 5
assert cart.get_total() == 7.50
def test_reject_negative_quantity(self):
"""Should validate quantity is positive."""
cart = ShoppingCart()
with pytest.raises(ValueError, match="Quantity must be positive"):
cart.add_item('apple', quantity=-1, price=1.50)
Input:
@tdd-guide
Analyze coverage:
[Coverage report data]
SF:src/auth/login.ts
DA:1,5
DA:2,5
DA:3,3
DA:4,0
DA:5,0
...
Target: 80% coverage
Output:
## Coverage Summary
- Line Coverage: 65.0%
- Branch Coverage: 58.3%
- Function Coverage: 75.0%
⚠️ **65.0%** coverage (yellow) - Below 80% threshold
## Recommendations
### 🔴 Critical (P0)
1. **Error handling paths not covered**
- Action: Add tests for authentication failure scenarios
- File: `src/auth/login.ts`
- Lines: 45-52, 67-70
2. **Branch coverage gap in validation**
- Action: Test all conditional branches in input validation
- File: `src/auth/login.ts`
- Lines: 23-28
### 🟡 Important (P1)
1. **Edge cases missing**
- Action: Add boundary tests for password length (7, 8, 9 chars)
- Impact: Medium
Input:
@tdd-guide
Guide TDD for email validation.
Requirement: Email must contain @ and valid domain
Phase: RED (write failing test)
Output:
## TDD Phase: RED
### Goal
Write a failing test that describes desired email validation behavior
### Steps
1. ✅ Read requirement: Email must contain @ and valid domain
2. ✅ Think about expected behavior
3. ⏳ Write test that verifies this behavior
4. ⏳ Run test and ensure it fails
5. ⏳ Verify failure reason is correct (not syntax error)
### Test Template (Jest)
```typescript
describe('EmailValidator', () => {
it('should accept valid email format', () => {
// Arrange
const validator = new EmailValidator();
// Act
const result = validator.validate('user@example.com');
// Assert
expect(result).toBe(true);
});
it('should reject email without @ symbol', () => {
const validator = new EmailValidator();
const result = validator.validate('userexample.com');
expect(result).toBe(false);
});
});
### Example 4: Test Quality Review
**Input**:
@tdd-guide
Review test quality:
def test_user_login(): result = login("admin", "password123") assert result assert result["status"] == "success" assert result["token"] assert result["user"]["id"] > 0 assert result["user"]["role"] == "admin"
**Output**:
```markdown
## Test Quality Analysis
**Overall Score**: 62/100
### Issues Detected
1. **Assertion Roulette** (High Severity)
- 5 assertions in single test
- **Fix**: Split into multiple focused tests
2. **Poor Test Isolation** (Medium Severity)
- Test depends on database state ("admin" user existing)
- **Fix**: Use fixtures or mocks for user data
3. **Weak Assertions** (Medium Severity)
- `assert result["token"]` just checks truthy (could be any string)
- **Fix**: `assert len(result["token"]) > 20` or use regex
4. **Missing Naming Context** (Low Severity)
- Test name doesn't describe what's being tested
- **Fix**: `test_successful_login_returns_valid_token_and_user_data`
### Recommended Refactoring
```python
@pytest.fixture
def admin_user():
return {"username": "admin", "password": "password123"}
def test_successful_login_returns_success_status(admin_user):
"""Test that valid credentials return success status."""
result = login(admin_user["username"], admin_user["password"])
assert result["status"] == "success"
def test_successful_login_returns_valid_jwt_token(admin_user):
"""Test that successful login returns a JWT token."""
result = login(admin_user["username"], admin_user["password"])
assert len(result["token"]) > 20
assert result["token"].count('.') == 2 # JWT format
def test_successful_login_returns_user_data(admin_user):
"""Test that successful login includes user information."""
result = login(admin_user["username"], admin_user["password"])
assert result["user"]["id"] > 0
assert result["user"]["role"] == "admin"
## Configuration
### Environment Variables
```bash
# Set preferred testing framework
export TDD_DEFAULT_FRAMEWORK="jest"
# Set coverage threshold
export TDD_COVERAGE_THRESHOLD=80
# Set output verbosity
export TDD_VERBOSE=true
# Set output format
export TDD_OUTPUT_FORMAT="markdown" # or "json", "terminal"
Create .tdd-guide.json in project root:
{
"framework": "jest",
"language": "typescript",
"coverage_threshold": 80,
"test_directory": "tests/",
"quality_rules": {
"max_assertions_per_test": 3,
"require_descriptive_names": true,
"enforce_isolation": true
},
"output": {
"format": "markdown",
"verbose": false,
"max_recommendations": 10
}
}
Issue: Generated tests have wrong syntax for my framework
Solution: Explicitly specify framework
Example: "Generate tests using Pytest" or "Framework: Jest"
Issue: Coverage report not recognized
Solution: Verify format (LCOV, JSON, XML)
Try: Paste raw coverage data instead of file path
Check: File exists and is readable
Issue: Too many recommendations, overwhelmed
Solution: Ask for prioritized output
Example: "Show only P0 (critical) recommendations"
Limit: "Top 5 recommendations only"
Issue: Test quality score seems wrong
Check: Ensure complete test context (setup/teardown included)
Verify: Test file contains actual test code, not just stubs
Context: Quality depends on isolation, assertions, naming
Issue: Framework detection incorrect
Solution: Specify framework explicitly
Example: "Using JUnit 5" or "Framework: Vitest"
Check: Ensure imports are present in code
tdd-guide/
├── SKILL.md # Skill definition (YAML + documentation)
├── README.md # This file
├── HOW_TO_USE.md # Usage examples
│
├── test_generator.py # Test generation core
├── coverage_analyzer.py # Coverage parsing and analysis
├── metrics_calculator.py # Quality metrics calculation
├── framework_adapter.py # Multi-framework support
├── tdd_workflow.py # Red-green-refactor guidance
├── fixture_generator.py # Test data and fixtures
├── format_detector.py # Automatic format detection
├── output_formatter.py # Context-aware output
│
├── sample_input_typescript.json # TypeScript example
├── sample_input_python.json # Python example
├── sample_coverage_report.lcov # LCOV coverage example
└── expected_output.json # Expected output structure
We welcome contributions! To contribute:
git checkout -b feature/improvement)python -m pytest tests/git commit -m "Add: feature description")git push origin feature/improvement)# Clone repository
git clone https://github.com/your-org/tdd-guide-skill.git
cd tdd-guide-skill
# Install development dependencies
pip install -r requirements-dev.txt
# Run tests
pytest tests/ -v
# Run linter
pylint *.py
# Run type checker
mypy *.py
MIT License - See LICENSE file for details
Built with Claude Skills Factory toolkit, following Test Driven Development best practices and informed by:
Ready to improve your testing workflow? Install the TDD Guide skill and start generating high-quality tests today!
View Count
0
Download Count
0
Favorite Count
0
Quality Score
69