Skip to main content
skill CX Codex

test-driven-development · bobmatnyc — Claude Code skill: setup and patterns

A testing skill for AI agents that enforces the Red-Green-Refactor loop, Arrange-Act-Assert patterns, naming conventions, and test coverage targets.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add bobmatnyc/claude-mpm-skills --skill test-driven-development -a claude-code
Open on GitHub

What test-driven-development does

The skill embeds standardized test-driven development practices into your agent workflow. It instructs the assistant to follow the strict Red-Green-Refactor cycle: produce a focused failing test first, implement the minimal logic required to pass, and refactor while keeping tests green. It also establishes structural templates like Arrange-Act-Assert and Given-When-Then, alongside naming patterns like test_should_<behavior>_when_<condition>.

It defines distinct boundaries across unit, integration, and end-to-end tests, with clear rules for stubs, fakes, and mocks. Target metrics require 100% coverage on critical paths and 95%+ on business logic, while strictly excluding framework internals and trivial getters from test suites.

Because the skill sets user-invocable: false and disable-model-invocation: true, you cannot run it as a standalone slash command. It operates as persistent background guidance whenever the model writes or refactors code.

What it helps with

  • enforce Red-Green-Refactor workflow on new features
  • structure test cases with Arrange-Act-Assert pattern
  • replace external databases and APIs with stubs or fakes
  • standardize test naming across team repositories

Example prompts for the agent

  • Implement the cart checkout using TDD, starting with a failing test
  • Write unit tests for the auth service following the Arrange-Act-Assert pattern
  • Refactor the order processor while keeping all test suites green

How to install test-driven-development

1Skills CLI (Vercel)

npx skills add bobmatnyc/claude-mpm-skills --skill test-driven-development -a claude-code

2Manually: put the files in place

~/.claude/skills/test-driven-development/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/test-driven-development/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about test-driven-development

How to install test-driven-development in Claude Code?

Run npx skills add bobmatnyc/claude-mpm-skills --skill test-driven-development -a claude-code in your terminal. The file is stored at ~/.claude/skills/test-driven-development/SKILL.md.

What does test-driven-development do?

It provides testing standards for the agent, covering the Red-Green-Refactor phases, mock strategies, test naming schemes, and target coverage percentages.

Can I invoke test-driven-development directly via slash command?

No. The frontmatter specifies user-invocable: false and disable-model-invocation: true. It acts as background rules whenever you instruct the agent to write or test code.

Source text

SKILL.md · Apache-2.0
---
name: test-driven-development
description: Comprehensive TDD patterns and practices for all programming languages, eliminating redundant testing guidance per agent.
user-invocable: false
disable-model-invocation: true
license: Apache-2.0
compatibility: claude-code
metadata:
  updated_at: 2025-10-30T17:00:00Z
tags: [testing, tdd, best-practices, quality-assurance]
progressive_disclosure:
  entry_point:
    summary: "Comprehensive TDD patterns and practices for all programming languages, eliminating redundant testing guidance per agent."
    when_to_use: "When writing tests, implementing test-driven-development, or ensuring code quality."
    quick_start: "1. Review the core concepts below. 2. Apply patterns to your use case. 3. Follow best practices for implementation."
  references:
    - anti-patterns.md
    - examples.md
    - integration.md
    - philosophy.md
    - workflow.md
---
# Test-Driven Development (TDD)

Comprehensive TDD patterns and practices for all programming languages. This skill eliminates ~500-800 lines of redundant testing guidance per agent.

## When to Use

Apply TDD for:
- New feature implementation
- Bug fixes (test the bug first)
- Code refactoring (tests ensure behavior preservation)
- API development (test contracts)
- Complex business logic

## TDD Workflow (Red-Green-Refactor)

### 1. Red Phase: Write Failing Test
```
Write a test that:
- Describes the desired behavior
- Fails for the right reason (not due to syntax errors)
- Is focused on a single behavior
```

### 2. Green Phase: Make It Pass
```
Write the minimum code to:
- Pass the test
- Not introduce regressions
- Follow existing patterns
```

### 3. Refactor Phase: Improve Code
```
While keeping tests green:
- Remove duplication
- Improve naming
- Simplify logic
- Extract functions/classes
```

## Test Structure Patterns

### Arrange-Act-Assert (AAA)
```
// 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-When-Then (BDD Style)
```
Given: A user with admin privileges
When: They attempt to access protected resource
Then: Access is granted with appropriate permissions
```

## Test Naming Conventions

### Pattern: `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()`

### Language-Specific Conventions

**Python (pytest):**
```python
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):**
```javascript
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:**
```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)
    }
}
```

## Test Types and Scope

### Unit Tests
- **Scope:** Single function/method
- **Dependencies:** Mocked
- **Speed:** Fast (< 10ms per test)
- **Coverage:** 80%+ of code paths

### Integration Tests
- **Scope:** Multiple components
- **Dependencies:** Real or test doubles
- **Speed:** Moderate (< 1s per test)
- **Coverage:** Critical paths and interfaces

### End-to-End Tests
- **Scope:** Full user workflows
- **Dependencies:** Real (in test environment)
- **Speed:** Slow (seconds to minutes)
- **Coverage:** Core user journeys

## Mocking and Test Doubles

### When to Mock
- External APIs and services
- Database operations (for unit tests)
- File system operations
- Time-dependent operations
- Random number generation

### Mock Types

**Stub:** Returns predefined data
```python
def get_user_stub(user_id):
    return User(id=user_id, name="Test User")
```

**Mock:** Verifies interactions
```python
mock_service = Mock()
service.process_payment(payment_data)
mock_service.process_payment.assert_called_once_with(payment_data)
```

**Fake:** Working implementation (simplified)
```python
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)
```

## Test Coverage Guidelines

### Target Coverage Levels
- **Critical paths:** 100%
- **Business logic:** 95%+
- **Overall project:** 80%+
- **UI components:** 70%+

### What to Test
- ✅ Business logic and algorithms
- ✅ Edge cases and boundary conditions
- ✅ Error handling and validation
- ✅ State transitions
- ✅ Public APIs and interfaces

### What NOT to Test
- ❌ Framework internals
- ❌ Third-party libraries
- ❌ Trivial getters/setters
- ❌ Generated code
- ❌ Configuration files

## Testing Best Practices

### 1. One Assertion Per Test (When Possible)
```python
# Good: Focused test
def test_should_validate_email_format():
    assert is_valid_email("[email protected]") is True

# Avoid: Multiple unrelated assertions
def test_validation():
    assert is_valid_email("[email protected]") is True
    assert is_valid_phone("123-456-7890") is True  # Different concept
```

### 2. Test Independence
```python
# Good: Each test is self-contained
def test_user_creation():
    user = create_user("[email protected]")
    assert user.email == "[email protected]"

# Avoid: Tests depending on execution order
shared_user = None

def test_create_user():
    global shared_user
    shared_user = create_user("[email protected]")

def test_update_user():  # Depends on previous test
    shared_user.name = "Updated"
```

### 3. Descriptive Test Failures
```python
# Good: Clear failure message
assert result.status == 200, f"Expected 200, got {result.status}: {result.body}"

# Avoid: Unclear failure
assert result.status == 200
```

### 4. Test Data Builders
```python
# Good: Reusable test data creation
def create_test_user(**overrides):
    defaults = {
        'email': '[email protected]',
        'name': 'Test User',
        'role': 'user'
    }
    return User(**{**defaults, **overrides})

# Usage
admin = create_test_user(role='admin')
guest = create_test_user(email='[email protected]')
```

## Testing Anti-Patterns to Avoid

### ❌ Testing Implementation Details
```python
# Bad: Tests internal structure
def test_user_storage():
    user = User("[email protected]")
    assert user._internal_cache is not None  # Implementation detail
```

### ❌ Fragile Tests
```python
# Bad: Breaks with harmless changes
assert user.to_json() == '{"name":"John","email":"[email protected]"}'

# Good: Tests behavior, not format
data = json.loads(user.to_json())
assert data['name'] == "John"
assert data['email'] == "[email protected]"
```

### ❌ Slow Tests in Unit Test Suite
```python
# 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
```

### ❌ Testing Everything Through UI
```python
# 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
```

## Quick Reference by Language

### Python (pytest)
```python
# Setup/Teardown
@pytest.fixture
def database():
    db = create_test_database()
    yield db
    db.cleanup()

# Parametrized tests
@pytest.mark.parametrize("input,expected", [
    ("[email protected]", True),
    ("invalid-email", False),
])
def test_email_validation(input, expected):
    assert is_valid_email(input) == expected
```

### JavaScript (Jest)
```javascript
// 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');
});
```

### Go
```go
// Table-driven tests
func TestEmailValidation(t *testing.T) {
    tests := []struct {
        input    string
        expected bool
    }{
        {"[email protected]", 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)
        }
    }
}
```

## TDD Benefits Realized

- **Design Improvement:** Tests drive better API design
- **Documentation:** Tests serve as executable documentation
- **Confidence:** Refactoring becomes safe
- **Debugging:** Tests isolate issues quickly
- **Coverage:** Ensures comprehensive test coverage
- **Regression Prevention:** Catches bugs before deployment

## Related Skills

When using Test Driven Development, these skills enhance your workflow:
- **systematic-debugging**: Debug-first methodology when tests fail unexpectedly
- **react**: Testing React components, hooks, and context
- **django**: Testing Django models, views, and forms
- **fastapi-local-dev**: Testing FastAPI endpoints and dependency injection

[Full documentation available in these skills if deployed in your bundle]

© bobmatnyc · Apache-2.0 · bobmatnyc/claude-mpm-skills

Similar skills

All skills for Testing and QA →

test-driven-development by other authors comes first.

test-driven-development Jesse Vincent This skill guides an agent through test-first development: verify a test fails, write the smallest passing change, then refactor. It covers features, bug fixes, and behavior changes. CX Codex 259,292installs test-driven-development addyosmani This skill guides work through red-green-refactor: write a failing test, add the smallest passing code, then refactor. Use it for logic, bugs, and behavior changes. CX Codex +1 62,000installs test-driven-development Hermes Agent (adapted from obra/superpowers) Skill that embeds TDD into your workflow: write the test first, watch it fail, then code. Forces you to see failing tests before implementation, reducing bugs and enabling safe refactoring. CX Codex +1 478installs test-driven-development sickn33 Guides coding agents through a strict test-driven development workflow: red, green, and refactor. Useful when fixing bugs or implementing new features with regression checks. CX Codex +1 1,400installs test-driven-development mikeyobrien This skill walks the agent through RED → GREEN → REFACTOR and makes it write tests before code. Useful when a spec or task needs to become checkable tests. CX Codex +1 ★ 3,189repo stars test-guard amElnagdy Reviews generated or edited test code against universal rules before commit or merge. It catches test bloat, over-mocking, and trivial tests in pytest, Jest, Vitest, Go, and PHPUnit suites. CX Codex +1 4,100installs unit-testing-framework aj-geddes A skill that gives the agent rules for writing unit tests: Arrange-Act-Assert structure, mocks, edge cases. Useful when a function or class needs coverage. CX Codex +1 593installs test-master https://github.com/Jeffallan A skill that walks an agent through writing unit, integration and E2E tests, reading coverage gaps and tracking down flaky failures. Handy when a project has thin test coverage. CX Codex +1 5,300installs test-analysis-extensions dotnet A reference catalog of per-language lookup tables for test analysis: markers, assertions, skips, sleep patterns. The agent reads the file matching your stack. CX Codex +1 3,100installs parallel-test-fixing spencerpauly The skill runs your test suite and assigns each failing test file to a separate subagent for parallel fixes. It helps when multiple test files break simultaneously across a codebase. CX Codex +1 412installs TDD Red Phase - Write Failing Tests First official github This subagent pulls GitHub issue context from branch names and creates failing tests for acceptance criteria before code is written. It enforces the red stage of TDD. ★ 40,451repo stars

From the same set97

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor