📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PHPUnit Testing Object Mother Pattern

Object Mother Pattern

5 min read
Centralise object creation in Object Mother classes: standard(), admin(), withEmail() factory methods.

Object Mother Pattern

class UserMother {
    public static function standard(): User {
        return new User(id:1, name:"Alice", email:"alice@example.com", role:"user");
    }
    public static function admin(): User {
        return new User(id:2, name:"Bob", email:"admin@example.com", role:"admin");
    }
    public static function withEmail(string $email): User {
        $user = self::standard();
        $user->email = $email;
        return $user;
    }
}

$admin = UserMother::admin();
$this->assertTrue($admin->isAdmin());