TDD & BDD
Test-Driven Development (TDD) and Behavior-Driven Development (BDD) are software development approaches that emphasize writing tests before writing code. They lead to better designed, more reliable software.
The TDD Cycle (Red-Green-Refactor)
TDD CYCLE
=========
+-------+ +--------+ +----------+
| RED |---->| GREEN |---->| REFACTOR |
+-------+ +--------+ +----------+
^ |
| |
+----------------------------+
RED: Write a failing test first
"What do I want to achieve?"
GREEN: Write minimal code to pass the test
"Make it work"
REFACTOR: Improve code while keeping tests green
"Make it clean"
Example:
1. RED: test_add(2, 3) == 5 (fails, no function yet)
2. GREEN: function add(a,b){ return a+b; } (passes)
3. REFACTOR: Extract to separate module, add docs
BDD - Behavior-Driven Development
BDD SCENARIO FORMAT
===================
Feature: User Login
Scenario: Successful login with valid credentials
Given I am on the login page
When I enter valid email and password
And I click the login button
Then I should be redirected to the dashboard
And I should see "Welcome back!"
Scenario: Failed login with wrong password
Given I am on the login page
When I enter valid email and wrong password
And I click the login button
Then I should see an error message
And I should remain on the login page
BDD uses natural language that all stakeholders understand.
TDD vs BDD
+----------------+---------------------------+---------------------------+
| Aspect | TDD | BDD |
+----------------+---------------------------+---------------------------+
| Focus | Code correctness | System behavior |
| Language | Programming language | Natural language (Gherkin)|
| Audience | Developers | Developers + Business |
| Tests | Unit tests | Acceptance tests |
| Tool | JUnit, pytest, Jest | Cucumber, SpecFlow |
+----------------+---------------------------+---------------------------+
Benefits of TDD/BDD
- Catches bugs early when they're cheap to fix
- Forces you to think about requirements before coding
- Creates a safety net for refactoring
- Produces living documentation through tests
- Leads to better code design through small, focused tests
Key Takeaways
- TDD follows the Red-Green-Refactor cycle
- BDD extends TDD with natural language scenarios
- Both approaches lead to more reliable, maintainable code
- Tests serve as living documentation