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 tests | With tests |
|---|---|
| Manually click through the app after every change to check nothing broke | Run one command; every rule you wrote is re-checked in seconds |
| Bugs are found by users in production | Bugs 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?
| Reason | What it means for you |
|---|---|
| Industry standard | The default testing tool for Laravel, Symfony, and most PHP projects |
| Catches regressions early | Run the whole suite before every commit or deploy |
| Documents behavior | A well-named test explains what the code is supposed to do |
| Enables confident refactoring | Change code structure without fear, as long as tests stay green |
Next steps: Head to Installation to add PHPUnit to a project via Composer.