Every time you change the code in your PHP project, you open the browser, fill in the same form, click Save, then look at the result. This is the tenth time today, and by now you aren't checking as carefully.
That job can be handed to PHPUnit, the standard testing framework for PHP: a test runner like Vitest. You write a method that runs your code, then state the result you expect through an assertion (a "this is how it should be" statement). Laravel (a web framework for PHP) installs PHPUnit when it creates a project. Picture a quality-control worker in a biscuit factory. Every biscuit is checked against a "this is how it should be" list. If it matches, it continues. If it doesn't, the worker sets it aside and writes down the reason. In this picture, the quality-control worker is PHPUnit, one biscuit is your code's result in one test, and the "this is how it should be" list is your assertion. PHPUnit also prints a dot for every test that passes, the letter F for each one that fails, and then writes down why.
A first test: class, method, assert
The code to test lives in app/Calculator.php:
<?php
namespace App;
class Calculator
{
public static function add($a, $b)
{
return $a + $b;
}
}
In PHP, variable names start with $. static means you call the method add directly on its class, Calculator::add(2, 3), without making an object first.
Its test lives in tests/Unit/CalculatorTest.php:
<?php
namespace Tests\Unit;
use App\Calculator;
use PHPUnit\Framework\TestCase;
class CalculatorTest extends TestCase
{
public function test_adds_two_numbers(): void
{
$this->assertEquals(5, Calculator::add(2, 3));
}
}
namespace Tests\Unit;gives the classes in this file a group name, andusebrings in a class from another group (much likeimportin JavaScript).class CalculatorTest extends TestCase: one test class, and its name ends inTest.extends TestCasemeans this class inherits fromTestCase, PHPUnit's base class, so every assertion method of PHPUnit can be used inside it.public function test_adds_two_numbers(): void: every method whose name starts withtestis one test.: voidmeans the method returns nothing. A method without that prefix doesn't run, unless it carries the#[Test]attribute (a marker written right above the method).$this->assertEquals(5, Calculator::add(2, 3)):$this->is the same asthis.in JavaScript: it calls a method of the test object itself. The expected value comes first, the value that actually comes out comes second. If the two differ, the test fails.
Running it and reading the result
Run it from the project folder with ./vendor/bin/phpunit (in Laravel, php artisan test works too). When everything matches:
PHPUnit 12.5.14 by Sebastian Bergmann and contributors.
Runtime: PHP 8.4.6
Configuration: /home/budi/calculator/phpunit.xml
. 1 / 1 (100%)
Time: 00:00.002, Memory: 26.50 MB
OK (1 test, 1 assertion)
This is PHPUnit 12, the version a Laravel 13 project installs. PHPUnit 13 has already been released.
Now say add is wrong: return $a . $b;. In PHP the dot joins text, so the result is '23'. PHPUnit writes:
PHPUnit 12.5.14 by Sebastian Bergmann and contributors.
Runtime: PHP 8.4.6
Configuration: /home/budi/calculator/phpunit.xml
F 1 / 1 (100%)
Time: 00:00.003, Memory: 26.50 MB
There was 1 failure:
1) Tests\Unit\CalculatorTest::test_adds_two_numbers
Failed asserting that '23' matches expected 5.
/home/budi/calculator/tests/Unit/CalculatorTest.php:12
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
- One character per test:
.passed,Fits assertion failed,Ethere was an error: an exception (an error thrown withthrow) that nobody caught. - Each failure gets a number, then the test's name, the reason, and the line of its assertion.
- The last line sums up: how many tests, how many assertions, how many failed.
assertEquals or assertSame?
Guess first: $this->assertEquals(5, '5') and $this->assertSame(5, '5'), which one passes?
The answer: assertEquals(5, '5') passes, assertSame(5, '5') fails.
assertEqualscompares loosely, like==: the number5and the text'5'count as the same.assertSamecompares strictly, like===: the value and its type must match. Its message:Failed asserting that '5' is identical to 5.
round(2 + 3, 2) gives the float (a decimal number) 5.0. assertEquals(5, 5.0) passes, but assertSame(5, 5.0) fails with Failed asserting that 5.0 is identical to 5. When the type matters, use assertSame.
Other assertions you'll use often
| Assertion | Passes when | Message when it fails |
|---|---|---|
assertTrue($x) / assertFalse($x) |
$x is exactly true / false |
Failed asserting that false is true. |
assertNull($x) |
$x is null |
|
assertCount(3, $arr) |
the array holds 3 items | Failed asserting that actual size 2 matches expected size 3. |
assertContains('apple', $arr) |
the array contains 'apple' |
Failed asserting that an array contains 'apple'. |
assertArrayHasKey('name', $arr) |
the array has the key name |
|
assertStringContainsString('Hello', $s) |
the text contains Hello |
|
assertGreaterThan(5, $x) |
$x is bigger than 5 |
Failed asserting that 3 is greater than 5. |
assertInstanceOf(User::class, $u) |
$u is a User object |
setUp(): prepared again before every test
When several tests need the same object, prepare that object in setUp(). PHPUnit calls setUp() before every test, like beforeEach in Vitest, so every test gets a fresh, clean object.
class CartTest extends TestCase
{
private Cart $cart;
protected function setUp(): void
{
parent::setUp();
$this->cart = new Cart();
}
protected function tearDown(): void
{
// clean up files or connections if there are any
parent::tearDown();
}
}
The order for two tests: setUp, test_one, tearDown, then setUp, test_two, tearDown. Don't remove parent::setUp(). That line runs the setUp() of TestCase, and TestCase (Laravel's especially) prepares a lot of things there.
Data provider: one test, many data
Instead of copying the same test for every number, move the data into a data provider: a method that returns a list of data for one test. The test below checks Calculator::isPrime, which says whether a number is a prime number:
use PHPUnit\Framework\Attributes\DataProvider;
public static function numberProvider(): array
{
return [
'two' => [2, true],
'four' => [4, false],
'seven' => [7, true],
'nine' => [9, false],
];
}
#[DataProvider('numberProvider')]
public function test_is_prime(int $number, bool $expected): void
{
$this->assertSame($expected, Calculator::isPrime($number));
}
- The provider is
public staticand returns an array of cases. Each case holds the arguments for the test method:$number, then$expected. #[DataProvider('numberProvider')]is a PHP 8 attribute that connects the provider to the test. PHPUnit runs the test once per case: four cases, four tests.- When one case fails, the name of that case is printed too:
Tests\Unit\CalculatorTest::test_is_prime@nine with data (9, false). That's what the key'nine'is for.
Testing an exception
The test below expects Calculator::divide(10, 0) to throw InvalidArgumentException, PHP's built-in exception for an argument that isn't valid:
public function test_divide_by_zero_is_refused(): void
{
$this->expectException(InvalidArgumentException::class);
Calculator::divide(10, 0);
}
expectException is written before the code that throws. The test passes when that exception really is thrown. When nothing is thrown, the message is: Failed asserting that exception of type "InvalidArgumentException" is thrown. In a file that has a namespace, add use InvalidArgumentException; at the top. Without that line, PHP looks for Tests\Unit\InvalidArgumentException, and the test is an E.
In the exercises: imitate the assertion yourself
The exercise sandbox runs plain PHP, without PHPUnit. So you write the check yourself and print its result:
function assertEquals($expected, $actual): string
{
return $expected === $actual ? "PASS" : "FAIL";
}
echo "1) " . assertEquals(5, 2 + 3) . "\n"; // 1) PASS
echo "3) " . assertEquals(10, 3 * 3) . "\n"; // 3) FAIL
- Compare with
$expected === $actual, so the type is checked too, as inassertSame. - To test
Calculator::add, store both values first:$expected = 5;and$actual = Calculator::add(2, 3);. Then print the result of the comparison:echo "assertEquals(5, Calculator::add(2, 3)): " . ($expected === $actual ? "PASS" : "FAIL") . "\n"; - For a data provider, write
numberProvider()that returns the array of cases, and a test function with the attribute#[DataProvider('numberProvider')]right above it. There's no PHPUnit to read that attribute. So you call the test for each case yourself,foreach (numberProvider() as $case) { echo testIsPrime(...$case) . "\n"; }, and print one line per case, for exampleassertTrue(isPrime(2)): PASS.
⚠️ When PHPUnit's results are confusing
- Arguments in the wrong order.
assertEquals($result, 5)still runs, but its message becomes misleading: "matches expected" points at your result, not at the value you expect. The expected value always comes first. assertEqualslets the wrong type through.'5'and5.0count as equal to5. UseassertSamewhen the type matters.- A test method without the
testprefix.public function addition()doesn't run at all. If the class still has other tests, there's no message about it. If it has no other test, PHPUnit only prints the warningNo tests found in class. - The old
@dataProviderannotation in a comment. PHPUnit 12 no longer reads annotations (old markers in a/** ... */comment), so the test is called without arguments and stops with anArgumentCountError. Use the#[DataProvider('...')]attribute, and make the providerstatic. The@testannotation is no longer read either: use#[Test]. expectExceptionafter the code. The exception is thrown before PHPUnit is told to expect it, so the test is anE, not a pass.
TL;DR: PHPUnit is a test runner for PHP. A test is written as a class ...Test extends TestCase (it inherits from PHPUnit's base class), and every test_...(): void method inside it is one test. That method calls $this->assert...(expected, actual), where $this is like this in JavaScript. Run it with ./vendor/bin/phpunit: . passed, F failed, E error. assertEquals compares loosely (==), assertSame strictly (===, the type is checked too). There are also assertTrue, assertFalse, assertCount, assertContains. setUp() runs before every test. #[DataProvider('providerName')] (an attribute: a marker above a method) runs one test for every case from a provider (a public static method that returns a list of cases). expectException(InvalidArgumentException::class) goes before the code that throws the exception (the error being thrown). In the exercise sandbox, imitate the assertion with === and then print PASS or FAIL with echo.
⚡ One test: class, method, assert
Write:
class CalculatorTest extends TestCase
{
public function test_adds_two_numbers(): void
{
$this->assertEquals(5, Calculator::add(2, 3));
}
}
Meaning: PHPUnit is a test runner for PHP. A PHPUnit test is a class whose name ends in Test and that inherits from TestCase, PHPUnit's base class. Every method whose name starts with test is one test. $this is the test object itself, like this in JavaScript. In assertEquals, the expected value (5) comes first, the value that actually comes out of Calculator::add(2, 3) second. Run it with ./vendor/bin/phpunit: . passed, F failed, E error.
⚡ assertEquals or assertSame
Guess first: of assertEquals(5, '5') and assertSame(5, '5') (a similar assertion), which one passes?
assertEquals passes, because it compares loosely, like ==: the number 5 and the text '5' count as the same. assertSame fails, because the type is checked too, like ===.
Meaning: When the type matters, use assertSame.
⚡ Data provider: one test, many data
Write:
#[DataProvider('numberProvider')]
public function test_is_prime(int $number, bool $expected): void
{
$this->assertSame($expected, Calculator::isPrime($number));
}
Meaning: numberProvider is a data provider: a public static method that returns a list of cases. The PHP 8 attribute #[DataProvider('numberProvider')] (a marker above a method) connects that provider to the test. PHPUnit runs the test once per case, with that case's values as $number and $expected: when the provider holds four cases, you get four tests.