← Back to PHP Course | Chapter 16: Testing & Tools | Lesson 1 of 10

PHP Unit Testing (PHPUnit)

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
<?php
function add($a, $b) {
    return $a + $b;
}
// A unit test would automatically check: add(2, 3) === 5
var_dump(add(2, 3) === 5);
?>

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
<?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";
?>

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
<?php
// $this->assertEquals(5, add(2, 3));
// $this->assertArrayHasKey('id', $user);
// $this->assertStringContainsString('Alice', $greeting);
echo "PHPUnit assertions produce clear failure messages";
?>

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
<?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";
?>

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
<?php
// Run in terminal: phpunit
echo "Scans for *Test.php files and reports a pass/fail summary";
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.