Lesson 2 of 9 · 24m
PHPUnit Essentials That Prevent Bad Habits
Modern PHPUnit attributes, precise assertions, data providers, exception testing, and configuration that keeps the suite honest.
PHPUnit is simple enough that most teams learn only the first 10 percent: extend TestCase, write methods starting with test, and run vendor/bin/phpunit. Then years pass. The result is a suite full of loose assertions, accidental dependencies, and warnings nobody reads.
Configure the suite you want to maintain
Modern PHPUnit belongs in phpunit.xml at the repository root:
<phpunit bootstrap="vendor/autoload.php" colors="true" executionOrder="random"
cacheDirectory=".phpunit.cache" failOnWarning="true" failOnRisky="true">
<testsuites>
<testsuite name="unit"><directory>tests/Unit</directory></testsuite>
<testsuite name="integration"><directory>tests/Integration</directory></testsuite>
</testsuites>
</phpunit>Random order and failure on risky tests matter. A test that passes only because another test ran first is not a passing test. It is a hidden dependency.
Assertions carry meaning
assertEquals asks whether two values look the same after type juggling rules. assertSame asks whether they are identical in type and value. Prefer the precise one.
self::assertSame(200, $response->getStatusCode()); self::assertTrue($user->isActive()); self::assertCount(3, $order->lines());Loose equality can hide a bug that later becomes a security bug. '0' == false is a lesson PHP developers learn once in production and should never relearn in tests.
Data providers are for orthogonal inputs
use PHPUnit\Framework\Attributes\DataProvider;
#[DataProvider('discountCases')]
public function test_discount_is_applied(int $subtotal, int $expected): void
{
self::assertSame($expected, Discount::forSubtotal($subtotal));
}
public static function discountCases(): iterable
{
yield 'no discount below threshold' => [999, 0];
yield 'ten percent wholesale' => [10000, 1000];
}The string keys matter: failure output names the business rule that broke.
Exceptions are behavior too
$this->expectException(InvalidQuantity::class);
new OrderLine(quantity: -1, unitPrice: Money::usd(500));Field notes
#[Test]andtestprefixes both work; pick one style. A test with no assertions is risky —expectNotToPerformAssertions()is for rare legacy cases. Assert exception type and a stable message fragment, never a full paragraph of copy.- Use
--testsuite unitlocally and reserve--testsuite integrationfor jobs that satisfy its dependencies. - If a test needs
#[Depends], question the design. Shared state between tests is usually a fixture problem.
Was this lesson helpful?