📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PHPUnit Testing setUp and tearDown

setUp and tearDown

5 min read Quiz at the end
Use setUp/tearDown per test and setUpBeforeClass/tearDownAfterClass for shared test fixtures.

setUp, tearDown, and Fixtures

class DatabaseTest extends TestCase {
    private PDO $db;
    private UserRepository $repo;

    // Runs BEFORE EACH test
    protected function setUp(): void {
        $this->db   = new PDO("sqlite::memory:");
        $this->db->exec("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)");
        $this->repo = new UserRepository($this->db);
    }

    // Runs AFTER EACH test
    protected function tearDown(): void {
        $this->db->exec("DROP TABLE IF EXISTS users");
        unset($this->db, $this->repo);
    }

    // Runs ONCE before ALL tests in class
    public static function setUpBeforeClass(): void {
        // expensive setup — shared across tests
    }

    // Runs ONCE after ALL tests in class
    public static function tearDownAfterClass(): void {
        // shared cleanup
    }

    public function testCreateUser(): void {
        $this->repo->create(["name" => "Alice", "email" => "a@b.com"]);
        $this->assertCount(1, $this->repo->all());
    }
}
Topic Quiz · 3 questions

Test your understanding before moving on

1. When does setUp() run?
💡 setUp() runs before every individual test method.
2. When does setUpBeforeClass() run?
💡 setUpBeforeClass() is static and runs once per class — good for expensive setup.
3. Why should tests be independent?
💡 Independent tests mean failures pinpoint exact issues without cascading.