📝 TDD Best Practices

Test-Driven Development

Test-Driven Development

TDD is a development approach where you write tests before code. Follow Red-Green-Refactor cycle for better design and fewer bugs.

💻 TDD Cycle

# Step 1: Write failing test (Red)
def test_add():
    result = add(2, 3)
    assert result == 5

# Step 2: Write minimal code to pass (Green)
def add(a, b):
    return a + b

# Step 3: Refactor
def add(a: int, b: int) -> int:
    """Add two numbers."""
    return a + b

# Repeat for each feature

�� Best Practices

# 1. One assert per test
def test_user_name():
    user = User('Alice')
    assert user.name == 'Alice'

def test_user_email():
    user = User('Alice', 'alice@ex.com')
    assert user.email == 'alice@ex.com'

# 2. Descriptive test names
def test_user_cannot_login_with_wrong_password():
    pass

# 3. AAA Pattern (Arrange, Act, Assert)
def test_withdrawal():
    # Arrange
    account = BankAccount(balance=100)
    # Act
    account.withdraw(30)
    # Assert
    assert account.balance == 70

# 4. Test edge cases
def test_divide_by_zero():
    with pytest.raises(ZeroDivisionError):
        divide(10, 0)

🎯 Key Takeaways