Skip to content
Tutorials Center
My learning

Topics

Lesson 121 of 147 ยท Modern PHP and Ecosystem

Testing PHP Code

Learn to test PHP code - assertions, a mini test runner you can run, PHPUnit and Pest syntax, data providers, test doubles, database tests and static analysis.

Every program gets tested. The only question is whether you test it with code, in seconds, every time you change something, or by clicking around by hand and hoping you didn't miss anything. Automated tests are small programs that call your code with known inputs and check the results. Once you have them, you can refactor, upgrade PHP or add features and know within seconds whether you broke something.

This lesson starts from first principles: you'll use assert(), then build a tiny test runner that you can run right here, so you understand exactly what a testing framework does. Then you'll see how the same tests look in PHPUnit and Pest, the two frameworks PHP developers actually use, learn to replace slow or unpredictable dependencies with test doubles, test database code against an in-memory SQLite database, and finally meet static analysis, which finds bugs without running anything.

Kinds of tests

Tests are usually grouped by how much of the system they exercise:

  • Unit tests check one function or class on its own. They're fast (thousands per second) and point straight at the broken piece.
  • Integration tests check that pieces work together: your repository class against a real database, or your code against a file system.
  • Feature or end-to-end tests drive the whole application, for example by sending a simulated HTTP request and checking the response, or by controlling a real browser.

Most projects aim for many unit tests, a good number of integration tests and fewer end-to-end tests, because the higher levels are slower and fail for more reasons. Every test, whatever its level, follows the same three steps, often called Arrange, Act, Assert: set up the inputs, call the code, check the outcome.

Your first checks with assert()

PHP has a built-in assert() that throws an AssertionError when its argument is false. It's a good way to see the basic idea of a test. Our editor runs with zend.assertions=1, so assertions are active:

PHP Checking a function with assert

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The third check fails, and that's the point of the example: the test found a real limitation. The function deletes accented letters instead of converting them, so 'รœnรฏcode Tรฏtle' becomes 'n-code-t-tle'. A test failing before you fix the code is exactly how bugs should be found.

Don't use assert() for checks your program needs in production. On production servers zend.assertions is normally -1, which removes assertions completely, so the expression inside isn't even evaluated. Validate input with if and exceptions; use assert() only for "this can never happen" checks during development (Debugging PHP).

A mini test runner

A testing framework isn't magic. It collects test functions, runs each one, catches failures so one broken test doesn't stop the others, and prints a report. Here's the core of one in about 40 lines. Tests are closures with descriptive names, and assertion helpers throw an exception with a clear message when a check fails:

PHP A tiny test framework

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Four tests pass and the last one fails on purpose, so you can see a failure report: expected 2000, got 1875. Because a test failed, the runner exits with code 1, just like PHPUnit and Pest do; that non-zero code is what makes a CI pipeline turn red. Delete the last test and the run exits with 0.

Notice the test names. A good name states the behavior, so a failure reads like a bug report: "FAIL rejects more than 100 percent" tells you what's broken without opening the code.

Table-driven tests

Many tests have the same shape with different data. Instead of copying the test, list the cases in an array and loop. PHPUnit calls this a data provider, Pest calls it a dataset. Here the same idea tests a validation function, with each case named so a failure points to the exact input:

PHP One test, many cases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

One case fails: "eve\n" is accepted, even though the test says it shouldn't be. In PCRE, $ also matches just before a final newline, so /^...$/ lets a trailing "\n" through. The fix is the D modifier (/^[a-z][a-z0-9_]{2,15}$/D) or \z instead of $. Add the D, run again, and all eight cases pass. Edge cases like this are why table-driven tests are worth writing: once the table exists, adding a tricky input costs one line.

PHPUnit

PHPUnit is the standard PHP testing framework, used directly or underneath almost every PHP project. Tests are methods in classes that extend TestCase; assertions are methods like assertSame(). You install it per project with Composer and run it from the command line:

Terminal
composer require --dev phpunit/phpunit
vendor/bin/phpunit                          # run all tests
vendor/bin/phpunit --filter=discount        # only matching tests
PHP
<?php
declare(strict_types=1);

namespace Tests\Unit;

use App\Pricing\DiscountCalculator;
use InvalidArgumentException;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;

final class DiscountCalculatorTest extends TestCase
{
    private DiscountCalculator $calculator;

    protected function setUp(): void          // runs before every test
    {
        $this->calculator = new DiscountCalculator();
    }

    #[Test]
    public function it_applies_a_percentage_discount(): void
    {
        $this->assertSame(1875, $this->calculator->apply(2500, 25));
    }

    #[Test]
    public function it_rejects_discounts_above_100_percent(): void
    {
        $this->expectException(InvalidArgumentException::class);

        $this->calculator->apply(2500, 150);
    }

    #[Test]
    #[DataProvider('roundingCases')]
    public function it_rounds_down_to_whole_cents(int $price, int $percent, int $expected): void
    {
        $this->assertSame($expected, $this->calculator->apply($price, $percent));
    }

    public static function roundingCases(): iterable
    {
        yield 'half off 999' => [999, 50, 499];
        yield 'one percent off 1' => [1, 1, 0];
    }
}

Modern PHPUnit marks tests and data providers with attributes (#[Test], #[DataProvider]); older code uses /** @test */ annotations or method names starting with test. A phpunit.xml file in the project root tells PHPUnit where tests live and how to bootstrap the autoloader. Use assertSame() (strict ===) rather than assertEquals() (loose ==) unless you really mean loose comparison: assertEquals(0, '') would hide a type bug.

Pest

Pest is built on top of PHPUnit and runs the same kind of tests with a shorter, function-based syntax and an expect() API that reads like a sentence. It's the default in new Laravel projects and popular elsewhere too:

PHP
<?php
use App\Pricing\DiscountCalculator;

beforeEach(function () {
    $this->calculator = new DiscountCalculator();
});

it('applies a percentage discount', function () {
    expect($this->calculator->apply(2500, 25))->toBe(1875);
});

it('rejects discounts above 100 percent', function () {
    $this->calculator->apply(2500, 150);
})->throws(InvalidArgumentException::class);

it('rounds down to whole cents', function (int $price, int $percent, int $expected) {
    expect($this->calculator->apply($price, $percent))->toBe($expected);
})->with([
    'half off 999' => [999, 50, 499],
    'one percent off 1' => [1, 1, 0],
]);

toBe() is strict like assertSame(). Because Pest runs on PHPUnit, both styles can live in the same project, and everything you learn about one transfers to the other.

Test doubles: fakes, stubs, mocks and spies

Real code talks to clocks, mail servers, payment APIs and databases. Tests that use the real thing are slow, can't run offline and give different results on different days. The fix is to design code so dependencies are passed in as interfaces (OOP Design Principles), then hand the code a stand-in during tests. Stand-ins are called test doubles, and there are a few kinds:

  • A stub returns canned answers ("the exchange rate is always 1.10").
  • A fake is a working but simplified implementation (an in-memory repository instead of a database).
  • A spy records how it was called, so the test can check afterwards.
  • A mock is set up with expectations in advance and fails the test if they aren't met. PHPUnit's createMock() and the Mockery library generate these.

This example tests a reminder service that depends on the current time and on sending email, two things you never want real in a unit test. A fixed clock (a stub) and a recording mailer (a spy) make the test fast and repeatable:

PHP A fixed clock and a spy mailer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Both checks print bool(true), and they will on any day you run them, because "now" is fixed at 10 May 2026. With the real clock, this test would start failing on its own after 20 May. Production code gets a SystemClock returning new DateTimeImmutable() and a mailer that really sends; the InvoiceReminder class never knows the difference.

Prefer simple hand-written fakes and spies like these over heavily configured mocks. A test that sets up ten mock expectations is tied to the implementation's every step and breaks whenever you refactor, even when the behavior is still correct.

Testing database code

For code that runs SQL, a stub hides exactly the part most likely to be wrong: the queries. Integration tests run them against a real database instead. SQLite in memory is perfect for this: each test creates a fresh database in microseconds, and it disappears afterwards. (If your production database is MySQL or PostgreSQL and you use their specific features, run these tests against that database in CI too.)

PHP An integration test with in-memory SQLite

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Each test starts with freshDatabase(), so no test depends on data left behind by another. That independence matters: tests that share state pass or fail depending on the order they run in, which is miserable to debug. Frameworks automate this by wrapping each test in a transaction that's rolled back afterwards (Transactions).

Static analysis: PHPStan and Psalm

Tests check the paths you thought of. Static analysers read your entire code base without running it and find whole classes of bugs: calling a method that doesn't exist, passing null where an object is required, forgetting a return, comparing values that can never be equal. The two main tools are PHPStan and Psalm:

Terminal
composer require --dev phpstan/phpstan
vendor/bin/phpstan analyse src tests --level=6
TEXT
 ------ ---------------------------------------------------------------
  Line   src/Billing/InvoiceService.php
 ------ ---------------------------------------------------------------
  42     Method App\Billing\InvoiceService::total() should return int
         but returns int|null.
  57     Call to an undefined method App\Billing\Invoice::getTotl().
 ------ ---------------------------------------------------------------

PHPStan has levels from 0 (basic checks) to 10 (strictest); Psalm counts the other way, from 8 (lenient) to 1 (strictest). Start an existing project at a low level, fix what's reported, and raise the level over time. A baseline file records today's errors so you can enforce the rules on new code immediately. Static analysis gets much more powerful with precise types, including PHPDoc types like list<string> and generics (The PHP Type System in Depth).

Two more tools round out a test setup. Code coverage (generated by Xdebug or PCOV through PHPUnit's --coverage-html) shows which lines your tests run, which is useful for finding untested code, though 100% coverage doesn't mean the assertions are any good. Mutation testing with Infection checks exactly that: it changes your code in small ways (flipping < to <=, say) and reports any change your tests didn't catch.

Making tests a habit

  • Run tests constantly. A suite that runs in seconds gets run after every change. Keep unit tests free of network, sleep and real time.
  • Run them in CI on every push, along with the style checker (Coding Standards and PSRs) and static analysis, so nothing broken reaches the main branch.
  • Write a test for every bug before fixing it. It proves you understood the bug, and it stays behind to keep the bug from coming back.
  • Test behavior, not implementation. Assert on results and visible effects, not on private details, so refactoring doesn't break tests.
  • Try test-driven development (TDD) for logic-heavy code: write a failing test, write just enough code to pass it, then clean up. It keeps code testable by design.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should a unit test give a service a fixed clock instead of letting it call new DateTimeImmutable()?

    Code that reads the real time behaves differently on different days, so its tests eventually fail on their own. Injecting a clock lets the test decide what "now" is.
  2. 2. What is the difference between assertSame(0, '') and assertEquals(0, '') in PHPUnit?

    assertSame uses strict comparison, so an int and a string are never the same. assertEquals uses loose comparison, which can hide type bugs. Prefer assertSame (or Pest's toBe).
  3. 3. A test double records every email address it was asked to send to, and the test checks that list afterwards. What kind of double is it?

    A spy records its calls so the test can inspect them after the code has run. A stub only returns canned answers.
  4. 4. Why does each database test in the lesson call freshDatabase()?

    Independent tests pass or fail on their own merits, regardless of the order they run in. Shared state causes tests that fail only sometimes.
  5. 5. What can static analysis tools like PHPStan find that tests might miss?

    Static analysers check every line without running it, including error branches your tests never reach. Formatting is the job of style fixers, and requirements need humans.

Summary

  • Automated tests call your code with known inputs and check the results, following Arrange, Act, Assert. Unit tests are fast and focused; integration and end-to-end tests check that parts work together.
  • assert() throws an AssertionError when assertions are enabled, but production usually disables them: never rely on it for real checks.
  • A test framework collects tests, isolates failures, prints a report and exits non-zero when anything fails, which is what CI looks for.
  • PHPUnit uses TestCase classes, #[Test] and #[DataProvider] attributes and assertSame(); Pest runs on PHPUnit with it(), expect()->toBe() and datasets.
  • Table-driven tests make edge cases cheap to add.
  • Inject dependencies through interfaces and replace them with stubs, fakes, spies or mocks; test SQL against a fresh in-memory SQLite database.
  • PHPStan and Psalm find type bugs without running code; coverage and mutation testing show how thorough your tests are.

Next: Design Patterns in PHP