Intermediate16 min read
Testing in PHP
Write unit and feature tests with PHPUnit and Pest, using mocks and coverage reports.
PHPUnit Basics
PHPUnit discovers test methods test* or annotated with #[Test]. assertEquals, assertTrue, and expectException verify behavior.
setUp and tearDown prepare fixtures. Data providers feed multiple cases into one test method.
Run vendor/bin/phpunit or artisan test in Laravel with parallel option for speed.
- Name tests after behavior, not methods
- Use factories for model test data
- Isolate tests—no shared mutable globals
public function test_discount_applies(): void
{
$this->assertSame(80.0, applyDiscount(100.0, 0.2));
}Mocks and Coverage
createMock builds test doubles implementing interfaces. expect calls with willReturn configures behavior.
Feature tests hit HTTP endpoints with Illuminate\Testing\TestResponse assertions in Laravel.
Coverage guides gaps but high percentage alone does not imply quality—focus on critical paths.
- Mock external HTTP with Http::fake in Laravel
- Use database transactions or RefreshDatabase trait
- Run tests in CI on every pull request