Overview
Automated tests protect behavior during refactoring and make regressions easier to locate. A custom PHP project can use PHPUnit without adopting a framework. Start with business rules and code that is easy to isolate.
Install and configure
Add PHPUnit as a development dependency using Composer, choosing a release compatible with the project's PHP version. Keep tests in a dedicated directory and define a repeatable test command in composer.json or project documentation.
Separate test types
Unit tests exercise a small unit with dependencies controlled or replaced. Integration tests verify interactions such as PDO queries against a test database. End-to-end tests exercise complete user workflows and are usually fewer because they are slower and more operationally complex.
Keep tests deterministic
Avoid depending on the current time, random external services or production data. Inject clocks and service clients where useful. Reset test data between tests and use a dedicated test database with credentials that cannot access production.
Test important failure paths
Test invalid input, missing records, authorization failures, database exceptions and boundary values—not only the happy path. A test should fail for the defect it is meant to catch.
Run tests before deployment
Run the suite locally and in CI. Combine tests with PHP syntax checks and static analysis. Do not disable a failing test merely to complete a deployment; understand whether the test or implementation is wrong.
Official references
PHPUnit documentation Composer scripts
Start with behavior that matters
Test domain rules and boundary behavior before trying to test every line. Unit tests should be fast and deterministic. Integration tests can verify PDO queries, file storage and mail adapters using controlled test dependencies.
A simple PHPUnit test
<?php
use PHPUnit\Framework\TestCase;
final class PriceCalculatorTest extends TestCase
{
public function testAppliesDiscount(): void
{
$calculator = new PriceCalculator();
self::assertSame(90.0, $calculator->discountedPrice(100.0, 10));
}
}
Pin the PHPUnit major version in Composer and consult its documentation for the PHP version compatibility matrix. Test code should not depend on production services or live customer data.
Keep tests independent
Each test should arrange its own data, execute one behavior and assert the result. Clean up temporary files and database rows. Avoid order-dependent tests and fixed sleeps; use controlled clocks or injected collaborators when time matters.
Add tests to the workflow
Run tests locally and in continuous integration. Keep a small fast suite for every change and a broader integration suite for release checks. When fixing a defect, add a regression test that fails before the fix and passes afterward.