PHPUnit Basics — Testing

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…

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));
    }
}

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.

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.

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));
}

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

⚠️ When PHPUnit's results are confusing

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.

What you will learn