| name | test-driven-development |
| description | Write tests before implementation code. Use when starting new features or fixing bugs. Covers Red-Green-Refactor cycle and TDD best practices. |
| allowed-tools | Read, Write, Edit, Bash, Glob, Grep |
Test-Driven Development
The TDD Cycle
- Red: Write a failing test
- Green: Write minimal code to pass
- Refactor: Improve code while keeping tests green
Workflows
TDD Example (Java + JUnit 5)
Step 1: Red - Write Failing Test
class CalculatorTest {
@Test
void add_TwoNumbers_ReturnsSum() {
Calculator calc = new Calculator();
int result = calc.add(2, 3);
assertThat(result).isEqualTo(5);
}
}
Step 2: Green - Minimal Implementation
public class Calculator {
public int add(int a, int b) {
return a + b;
}
}
Step 3: Refactor (if needed)
Code is already clean, move to next test.
Step 4: Next Test
@Test
void subtract_TwoNumbers_ReturnsDifference() {
Calculator calc = new Calculator();
int result = calc.subtract(5, 3);
assertThat(result).isEqualTo(2);
}
Step 5: Implement Subtract
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
}
TDD Benefits
- Design Feedback: Tests reveal design issues early
- Documentation: Tests document expected behavior
- Confidence: Refactor fearlessly with test safety net
- Focus: One behavior at a time
TDD Tips
- Start Simple: Begin with the simplest test case
- One Assert: Each test should verify one behavior
- Descriptive Names: Test names are documentation
- No Logic in Tests: Tests should be obvious
- Fast Feedback: Tests should run in milliseconds
When to Use TDD
- New features with clear requirements
- Bug fixes (write failing test first)
- Complex business logic
- API contract development
When TDD is Less Useful
- Exploratory/prototype code
- UI layout changes
- Simple CRUD operations