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.
- If PHPUnit cannot find your classes, ensure Composer autoload is configured and run
composer dump-autoload.