Learning PHPUnit for automated testing. How to run the examples and notes on common patterns to reference from.
-
Install PHPUnit as a dev dependency (recommended):
composer require --dev phpunit/phpunit
-
Running tests:
./vendor/bin/phpunit [tests/path]
- Tests live under
tests/. - Files/classes should be named
SomethingTest.phpand test classesSomethingTestto match. - Each test file will extend on the
PHPUnit\Framework\TestCase.
- assertSame(expected, actual) — strict type and value equality
- assertEquals(expected, actual) — loose equality
- assertTrue / assertFalse
- assertNull / assertNotNull
- assertCount(expected, array)
- assertInstanceOf(Class::class, $obj)
- assertStringContainsString(substr, string)
- Keep tests small and focused (one assertion intent per test when possible).
assertSamefor primitives to avoid type-coercion.- Use
setUpto reduce duplication, but avoid hiding important setup in multiple layers.
- Use the
setUp()method to create fixtures used by many tests andtearDown()to clean up.
protected function setUp(): void
{
// runs before each test
}
protected function tearDown(): void
{
// runs after each test
}- Add
@group nameto tests and run with--group nameto run only that group, seephpunit.xml.distexcluding the group named excluded.
- Definition: A programmable stand-in for a real dependency.
- Behavior: Returns exactly what you tell data/errors to isolate your code.
- External Issues: Real service is slow, flaky, or unavailable.
- Simulation: Testing edge cases (errors, timeouts, specific payloads).
- Efficiency: When you need tests to be fast and deterministic.
- Isolation: Focuses testing on your logic, not external systems.
- Speed: Skips heavy processing and network latency.
- Reliability: Eliminates test flakiness caused by third-party outages.
- If PHPUnit cannot find your classes, ensure Composer autoload is configured and run
composer dump-autoload.