PHP Unit Testing (PHPUnit)
In this page:
Introduction to Unit Testing
Unit testing checks small, isolated pieces of code -- typically a single function or method -- in automated fashion, catching regressions the moment a change breaks something instead of during manual QA weeks later.
Example: Introduction to Unit Testing
<?php
function add($a, $b) {
return $a + $b;
}
// A unit test would automatically check: add(2, 3) === 5
var_dump(add(2, 3) === 5);
?>
Login to try C/C++/Java/PHP code in the editor
Writing your First Test
A PHPUnit test class extends TestCase and defines methods (conventionally prefixed with test) that each exercise one specific behavior and assert what the correct outcome should be.
Example: Writing your First Test
<?php
// use PHPUnit\Framework\TestCase;
// class MathTest extends TestCase {
// public function testAddition() {
// $this->assertEquals(5, add(2, 3));
// }
// }
echo "A PHPUnit test class extends TestCase";
?>
Login to try C/C++/Java/PHP code in the editor
Test Assertions
PHPUnit ships dozens of purpose-built assertions -- assertEquals, assertArrayHasKey, assertStringContainsString -- that produce far more informative failure messages than a bare if-check ever could.
Example: Test Assertions
<?php
// $this->assertEquals(5, add(2, 3));
// $this->assertArrayHasKey('id', $user);
// $this->assertStringContainsString('Alice', $greeting);
echo "PHPUnit assertions produce clear failure messages";
?>
Login to try C/C++/Java/PHP code in the editor
Testing Setup and Teardown
setUp() runs before every single test method to prepare fresh fixtures (like a clean database connection), and tearDown() runs after each one to clean up, keeping tests fully isolated from each other.
Example: Testing Setup and Teardown
<?php
// protected function setUp(): void { $this->db = new SQLite3(':memory:'); }
// protected function tearDown(): void { $this->db->close(); }
echo "setUp runs before, tearDown runs after each test method";
?>
Login to try C/C++/Java/PHP code in the editor
Running PHPUnit
Running phpunit from the terminal scans your test directory for files matching *Test.php and executes every test method it finds, reporting a pass/fail summary for the whole suite in one command.
Example: Running PHPUnit
<?php
// Run in terminal: phpunit
echo "Scans for *Test.php files and reports a pass/fail summary";
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: