Unit Testing PHP Code with PHPUnit

Untested PHP code tends to accumulate “don’t touch this, it’s fragile” comments. PHPUnit has been the standard testing framework for PHP for nearly two decades, and getting a basic test suite running takes only a few minutes.

composer require --dev phpunit/phpunit
./vendor/bin/phpunit --version
use PHPUnit\Framework\TestCase;

class CartTest extends TestCase {
    public function testAddingItemsIncreasesTotal(): void {
        $cart = new Cart();
        $cart->add(new Product('Widget', 9.99), 2);

        $this->assertEquals(19.98, $cart->getTotal());
    }

    public function testEmptyCartHasZeroTotal(): void {
        $cart = new Cart();
        $this->assertEquals(0, $cart->getTotal());
    }
}
./vendor/bin/phpunit tests/

Start with the code that changes most often and breaks most quietly — usually business logic like pricing, permissions, or data transformations — rather than trying to reach 100% coverage on day one.