Predict the TDD Process
Intermediate · Predict the output · from Test-Driven Development: Write the Test First, Then the Code
From the lesson: Test-Driven Development: Write the Test First, Then the Code
Imagine you're drawing a picture. Most people sketch the outline first, then fill in the colors. You wouldn't start by painting random patches of blue and hope a sky appears.
Read the lessonThis code simulates a TDD process with a test runner that reports RED or GREEN for each cycle. Read carefully and predict what gets printed.
def run_tdd_cycle(name, test_fn, impl_fn=None):
if impl_fn:
impl_fn()
try:
test_fn()
print(f'GREEN: {name}')
except Exception:
print(f'RED: {name}')
functions = {}
def test_celsius():
assert functions['to_celsius'](32) == 0.0
def test_boiling():
assert functions['to_celsius'](212) == 100.0
# Cycle 1: RED (function doesn't exist yet)
run_tdd_cycle('celsius_basic', test_celsius)
# Cycle 1: GREEN (add the function)
def add_celsius():
functions['to_celsius'] = lambda f: (f - 32) * 5 / 9
run_tdd_cycle('celsius_basic', test_celsius, add_celsius)
# Cycle 2: Does boiling point work too?
run_tdd_cycle('celsius_boiling', test_boiling)
More TDD exercises
- Your First TDD CycleIntermediate
- TDD: Build a Password ValidatorAdvanced
- TDD Bug Fix: Reproduce Then FixAdvanced
- TDD Challenge: Build a Word CounterAdvanced