PHPUnit Tutorial

PHPUnit is the most widely used testing framework for PHP. It lets you write small, automated checks — tests — that verify your code behaves the way you expect, and re-run all of them in seconds any time you change something.

Where this fits: PHPUnit is installed via Composer as a dev dependency (composer require --dev phpunit/phpunit) — if that sounds unfamiliar, the Composer track covers exactly this on its Dev Dependencies page.

Why Write Automated Tests?

Without testsWith tests
Manually click through the app after every change to check nothing brokeRun one command; every rule you wrote is re-checked in seconds
Bugs are found by users in productionBugs are caught before the code is even committed
Refactoring feels risky — did I break something?Refactor confidently — the test suite tells you immediately if you did
Behavior is only documented in comments (if at all)Tests double as living, always-accurate documentation of expected behavior

A Quick Look Ahead

Example: A Simple Test Case

<?php
use PHPUnit\Framework\TestCase;

class CalculatorTest extends TestCase
{
    public function testAddsTwoNumbers()
    {
        $calculator = new Calculator();
        $this->assertEquals(5, $calculator->add(2, 3));
    }
}

Example: Running It

./vendor/bin/phpunit tests/CalculatorTest.php
Note: This is correct, real PHPUnit code — but this website's own project doesn't have PHPUnit installed, so you won't see it actually run on this page. Follow along in your own project after the next page's installation steps.

Why Learn PHPUnit?

ReasonWhat it means for you
Industry standardThe default testing tool for Laravel, Symfony, and most PHP projects
Catches regressions earlyRun the whole suite before every commit or deploy
Documents behaviorA well-named test explains what the code is supposed to do
Enables confident refactoringChange code structure without fear, as long as tests stay green
Next steps: Head to Installation to add PHPUnit to a project via Composer.