Site Tools


swe:test-driven-development

Table of Contents

Test-driven development

Test-driven development is a practice where you write the test before you write the code. The cycle is red-green-refactor: write a failing test, write minimum code to make it pass, then clean up the code while keeping tests green.

Code written without tests in mind is often hard to test. Functions end up with too many responsibilities, dependencies are hard-coded, and internal state is not injectable, making it impossible to test in isolation. Writing tests after the code is complete means only the easy paths get tested and awkward corners get skipped.

Writing tests first forces you to design for testability from the start. You must decide the function signature and behaviour before implementing it, which produces cleaner interfaces. Every line of production code exists to satisfy a test, preventing dead code written “for future use”.

The red-green-refactor cycle: write failing tests, write minimum code to pass, then improve the code while keeping tests green.

# Red: Write failing test first
def test_email_validator_rejects_invalid():
    assert not is_valid_email("not-an-email")
    assert not is_valid_email("missing@domain")
 
# Green: Minimum code to pass test
def is_valid_email(email):
    return '@' in email and '.' in email.split('@')[1]
 
# Refactor: Clean up while keeping tests passing
import re
def is_valid_email(email):
    pattern = r'^[^@]+@[^@]+\.[^@]+$'
    return bool(re.match(pattern, email))
swe/test-driven-development.md · Last modified: by 127.0.0.1