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());
}
}