📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PHPUnit Testing TDD — Test Driven Development

TDD — Test Driven Development

6 min read Quiz at the end
Follow TDD Red-Green-Refactor: write a failing test, pass it with minimal code, then refactor.

Test-Driven Development

TDD cycle: Red → Green → Refactor

// 1. RED — Write a failing test first
public function testPasswordMustHaveUppercase(): void {
    $validator = new PasswordValidator();
    $this->assertFalse($validator->validate("alllowercase1!"));
}

// 2. GREEN — Write minimum code to pass
class PasswordValidator {
    public function validate(string $password): bool {
        return preg_match("/[A-Z]/", $password) === 1;
    }
}

// 3. REFACTOR — improve without breaking tests
class PasswordValidator {
    private array $rules = [
        "uppercase" => "/[A-Z]/",
        "digit"     => "/[0-9]/",
        "special"   => "/[!@#$%]/",
        "length"    => "/.{8,}/",
    ];

    public function validate(string $password): bool {
        foreach ($this->rules as $rule => $pattern) {
            if (!preg_match($pattern, $password)) return false;
        }
        return true;
    }
}

// 4. Repeat for next feature
Topic Quiz · 2 questions

Test your understanding before moving on

1. What is the TDD cycle?
💡 TDD: Red (failing test) Green (minimal code to pass) Refactor (clean up).
2. In TDD, when do you write the test?
💡 TDD requires writing the failing test FIRST before any production code.