Test-Driven Development (TDD)
Overview
TDD is a workflow where tests are written before production code in short cycles: Red, Green, Refactor.
TDD Cycle
flowchart LR
A[Red - Write Failing Test] --> B[Green - Minimal Code]
B --> C[Refactor - Improve Design]
C --> A
Practical Example
Step 1 - failing test:
[Fact]
public void AppliesLoyaltyDiscount()
{
Assert.Equal(90m, ApplyDiscount(100m, "LOYAL"));
}
Step 2 - minimal implementation:
private static decimal ApplyDiscount(decimal total, string tier)
{
return tier == "LOYAL" ? 90m : total;
}
Step 3 - refactor for clarity and extensibility.
Production Guidance
- Keep cycles short and focused
- Use tests to define behavior, not internal structure
- Refactor immediately after passing tests
Common Pitfalls
- Writing overly broad tests that validate too many rules
- Skipping refactor step after green
- Treating TDD as mandatory for every low-risk change
Key Takeaways
- TDD improves design feedback and regression safety.
- Small cycles reduce risk during feature development.
- Refactoring is a required part of the method.