test-driven-development by bobmatnyc/claude-mpm-skills
npx skills add https://github.com/bobmatnyc/claude-mpm-skills --skill test-driven-development适用于所有编程语言的全面 TDD 模式与实践。此技能为每个智能体消除了约 500-800 行冗余的测试指导。
在以下场景应用 TDD:
编写一个测试,该测试:
- 描述期望的行为
- 因正确的原因而失败(非语法错误)
- 专注于单一行为
编写最少的代码以:
- 通过测试
- 不引入回归问题
- 遵循现有模式
在保持测试通过的同时:
- 消除重复
- 改进命名
- 简化逻辑
- 提取函数/类
// Arrange: 设置测试数据和条件
const user = createTestUser({ role: 'admin' });
// Act: 执行被测试的操作
const result = await authenticateUser(user);
// Assert: 验证结果
expect(result.isAuthenticated).toBe(true);
expect(result.permissions).toContain('admin');
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
Given: 一个具有管理员权限的用户
When: 他们尝试访问受保护资源
Then: 授予访问权限并附带适当的权限
test_should_<期望的行为>_when_<条件>示例:
test_should_return_user_when_id_exists()test_should_raise_error_when_user_not_found()test_should_validate_email_format_when_creating_account()Python (pytest):
def test_should_calculate_total_when_items_added():
# Arrange
cart = ShoppingCart()
cart.add_item(Item("Book", 10.00))
cart.add_item(Item("Pen", 1.50))
# Act
total = cart.calculate_total()
# Assert
assert total == 11.50
JavaScript (Jest):
describe('ShoppingCart', () => {
test('should calculate total when items added', () => {
const cart = new ShoppingCart();
cart.addItem({ name: 'Book', price: 10.00 });
cart.addItem({ name: 'Pen', price: 1.50 });
const total = cart.calculateTotal();
expect(total).toBe(11.50);
});
});
Go:
func TestShouldCalculateTotalWhenItemsAdded(t *testing.T) {
// Arrange
cart := NewShoppingCart()
cart.AddItem(Item{Name: "Book", Price: 10.00})
cart.AddItem(Item{Name: "Pen", Price: 1.50})
// Act
total := cart.CalculateTotal()
// Assert
if total != 11.50 {
t.Errorf("Expected 11.50, got %f", total)
}
}
存根: 返回预定义数据
def get_user_stub(user_id):
return User(id=user_id, name="Test User")
模拟: 验证交互
mock_service = Mock()
service.process_payment(payment_data)
mock_service.process_payment.assert_called_once_with(payment_data)
伪造: 可工作的实现(简化版)
class FakeDatabase:
def __init__(self):
self.data = {}
def save(self, key, value):
self.data[key] = value
def get(self, key):
return self.data.get(key)
# 好:专注的测试
def test_should_validate_email_format():
assert is_valid_email("user@example.com") is True
# 避免:多个不相关的断言
def test_validation():
assert is_valid_email("user@example.com") is True
assert is_valid_phone("123-456-7890") is True # 不同的概念
# 好:每个测试都是独立的
def test_user_creation():
user = create_user("test@example.com")
assert user.email == "test@example.com"
# 避免:测试依赖于执行顺序
shared_user = None
def test_create_user():
global shared_user
shared_user = create_user("test@example.com")
def test_update_user(): # 依赖于之前的测试
shared_user.name = "Updated"
# 好:清晰的失败信息
assert result.status == 200, f"Expected 200, got {result.status}: {result.body}"
# 避免:不清晰的失败信息
assert result.status == 200
# 好:可重用的测试数据创建
def create_test_user(**overrides):
defaults = {
'email': 'test@example.com',
'name': 'Test User',
'role': 'user'
}
return User(**{**defaults, **overrides})
# 用法
admin = create_test_user(role='admin')
guest = create_test_user(email='guest@example.com')
# 差:测试内部结构
def test_user_storage():
user = User("test@example.com")
assert user._internal_cache is not None # 实现细节
# 差:无害的更改就会导致失败
assert user.to_json() == '{"name":"John","email":"john@example.com"}'
# 好:测试行为,而非格式
data = json.loads(user.to_json())
assert data['name'] == "John"
assert data['email'] == "john@example.com"
# 差:单元测试中进行真实的 HTTP 调用
def test_api_integration():
response = requests.get("https://api.example.com/users") # 慢!
assert response.status_code == 200
# 差:通过 UI 测试业务逻辑
def test_calculation():
browser.click("#input1")
browser.type("5")
browser.click("#input2")
browser.type("3")
browser.click("#calculate")
assert browser.find("#result").text == "8"
# 好:直接测试逻辑
def test_calculation():
assert calculate(5, 3) == 8
# Setup/Teardown
@pytest.fixture
def database():
db = create_test_database()
yield db
db.cleanup()
# 参数化测试
@pytest.mark.parametrize("input,expected", [
("user@example.com", True),
("invalid-email", False),
])
def test_email_validation(input, expected):
assert is_valid_email(input) == expected
// Setup/Teardown
beforeEach(() => {
database = createTestDatabase();
});
afterEach(() => {
database.cleanup();
});
// 异步测试
test('should fetch user data', async () => {
const user = await fetchUser(1);
expect(user.name).toBe('John');
});
// 表格驱动测试
func TestEmailValidation(t *testing.T) {
tests := []struct {
input string
expected bool
}{
{"user@example.com", true},
{"invalid-email", false},
}
for _, tt := range tests {
result := IsValidEmail(tt.input)
if result != tt.expected {
t.Errorf("IsValidEmail(%s) = %v, want %v",
tt.input, result, tt.expected)
}
}
}
使用测试驱动开发时,这些技能可以增强您的工作流程:
[完整文档可在您捆绑包中部署的这些技能中找到]
每周安装次数
94
代码仓库
GitHub 星标数
20
首次出现
2026年1月23日
安全审计
安装于
opencode75
gemini-cli73
claude-code72
codex72
github-copilot70
cursor69
Comprehensive TDD patterns and practices for all programming languages. This skill eliminates ~500-800 lines of redundant testing guidance per agent.
Apply TDD for:
Write a test that:
- Describes the desired behavior
- Fails for the right reason (not due to syntax errors)
- Is focused on a single behavior
Write the minimum code to:
- Pass the test
- Not introduce regressions
- Follow existing patterns
While keeping tests green:
- Remove duplication
- Improve naming
- Simplify logic
- Extract functions/classes
// Arrange: Set up test data and conditions
const user = createTestUser({ role: 'admin' });
// Act: Perform the action being tested
const result = await authenticateUser(user);
// Assert: Verify the outcome
expect(result.isAuthenticated).toBe(true);
expect(result.permissions).toContain('admin');
Given: A user with admin privileges
When: They attempt to access protected resource
Then: Access is granted with appropriate permissions
test_should_<expected_behavior>_when_<condition>Examples:
test_should_return_user_when_id_exists()test_should_raise_error_when_user_not_found()test_should_validate_email_format_when_creating_account()Python (pytest):
def test_should_calculate_total_when_items_added():
# Arrange
cart = ShoppingCart()
cart.add_item(Item("Book", 10.00))
cart.add_item(Item("Pen", 1.50))
# Act
total = cart.calculate_total()
# Assert
assert total == 11.50
JavaScript (Jest):
describe('ShoppingCart', () => {
test('should calculate total when items added', () => {
const cart = new ShoppingCart();
cart.addItem({ name: 'Book', price: 10.00 });
cart.addItem({ name: 'Pen', price: 1.50 });
const total = cart.calculateTotal();
expect(total).toBe(11.50);
});
});
Go:
func TestShouldCalculateTotalWhenItemsAdded(t *testing.T) {
// Arrange
cart := NewShoppingCart()
cart.AddItem(Item{Name: "Book", Price: 10.00})
cart.AddItem(Item{Name: "Pen", Price: 1.50})
// Act
total := cart.CalculateTotal()
// Assert
if total != 11.50 {
t.Errorf("Expected 11.50, got %f", total)
}
}
Stub: Returns predefined data
def get_user_stub(user_id):
return User(id=user_id, name="Test User")
Mock: Verifies interactions
mock_service = Mock()
service.process_payment(payment_data)
mock_service.process_payment.assert_called_once_with(payment_data)
Fake: Working implementation (simplified)
class FakeDatabase:
def __init__(self):
self.data = {}
def save(self, key, value):
self.data[key] = value
def get(self, key):
return self.data.get(key)
# Good: Focused test
def test_should_validate_email_format():
assert is_valid_email("user@example.com") is True
# Avoid: Multiple unrelated assertions
def test_validation():
assert is_valid_email("user@example.com") is True
assert is_valid_phone("123-456-7890") is True # Different concept
# Good: Each test is self-contained
def test_user_creation():
user = create_user("test@example.com")
assert user.email == "test@example.com"
# Avoid: Tests depending on execution order
shared_user = None
def test_create_user():
global shared_user
shared_user = create_user("test@example.com")
def test_update_user(): # Depends on previous test
shared_user.name = "Updated"
# Good: Clear failure message
assert result.status == 200, f"Expected 200, got {result.status}: {result.body}"
# Avoid: Unclear failure
assert result.status == 200
# Good: Reusable test data creation
def create_test_user(**overrides):
defaults = {
'email': 'test@example.com',
'name': 'Test User',
'role': 'user'
}
return User(**{**defaults, **overrides})
# Usage
admin = create_test_user(role='admin')
guest = create_test_user(email='guest@example.com')
# Bad: Tests internal structure
def test_user_storage():
user = User("test@example.com")
assert user._internal_cache is not None # Implementation detail
# Bad: Breaks with harmless changes
assert user.to_json() == '{"name":"John","email":"john@example.com"}'
# Good: Tests behavior, not format
data = json.loads(user.to_json())
assert data['name'] == "John"
assert data['email'] == "john@example.com"
# Bad: Real HTTP calls in unit tests
def test_api_integration():
response = requests.get("https://api.example.com/users") # Slow!
assert response.status_code == 200
# Bad: Testing business logic through UI
def test_calculation():
browser.click("#input1")
browser.type("5")
browser.click("#input2")
browser.type("3")
browser.click("#calculate")
assert browser.find("#result").text == "8"
# Good: Test logic directly
def test_calculation():
assert calculate(5, 3) == 8
# Setup/Teardown
@pytest.fixture
def database():
db = create_test_database()
yield db
db.cleanup()
# Parametrized tests
@pytest.mark.parametrize("input,expected", [
("user@example.com", True),
("invalid-email", False),
])
def test_email_validation(input, expected):
assert is_valid_email(input) == expected
// Setup/Teardown
beforeEach(() => {
database = createTestDatabase();
});
afterEach(() => {
database.cleanup();
});
// Async tests
test('should fetch user data', async () => {
const user = await fetchUser(1);
expect(user.name).toBe('John');
});
// Table-driven tests
func TestEmailValidation(t *testing.T) {
tests := []struct {
input string
expected bool
}{
{"user@example.com", true},
{"invalid-email", false},
}
for _, tt := range tests {
result := IsValidEmail(tt.input)
if result != tt.expected {
t.Errorf("IsValidEmail(%s) = %v, want %v",
tt.input, result, tt.expected)
}
}
}
When using Test Driven Development, these skills enhance your workflow:
[Full documentation available in these skills if deployed in your bundle]
Weekly Installs
94
Repository
GitHub Stars
20
First Seen
Jan 23, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode75
gemini-cli73
claude-code72
codex72
github-copilot70
cursor69
Vue 3 调试指南:解决响应式、计算属性与监听器常见错误
11,800 周安装