testing php applications
PHPUnit Assertions
Assertions express the observable outcome a test expects. The best assertion is usually the narrowest one that communicates a useful failure message.
Prefer Precise Comparisons
assertSame() checks value and type, which is often safer than loose equality. PHPUnit also includes assertions for counts, arrays, strings, files, exceptions, objects, and many other conditions.
Make Failures Explain The Problem
One clear assertion can be better than several broad assertions. When a test needs several values, use assertions that identify the broken part of the response or domain result.
PHP example
<?php
declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class ProductResultTest extends TestCase
{
public function testPublishedProductContainsExpectedFields(): void
{
$product = ['id' => 42, 'name' => 'Desk lamp', 'published' => true];
$this->assertSame(42, $product['id']);
$this->assertSame('Desk lamp', $product['name']);
$this->assertTrue($product['published']);
$this->assertArrayNotHasKey('deleted_at', $product);
}
}
Common Mistakes
- Using loose comparisons when type matters.
- Asserting only that a response is not null.
- Writing many assertions against unrelated behaviours in one test.
- Forgetting a message or precise assertion when diagnosis would otherwise be difficult.
What To Practise
- Choose precise assertions.
- Use strict comparisons for typed values.
- Keep assertions tied to one behaviour.
Practice
Practice: Choose Assertions For A Product Result
Write and run a PHPUnit test for a published product result returned by a service.
Requirements
- Check ID strictly.
- Check name.
- Check published status.
- Check a missing optional field deliberately.
Show solution
Use assertions that make the expected shape and types explicit.
PHP example
<?php
declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class ProductResultTest extends TestCase
{
public function testPublishedProductContainsExpectedFields(): void
{
$product = ['id' => 42, 'name' => 'Desk lamp', 'published' => true];
$this->assertSame(42, $product['id']);
$this->assertSame('Desk lamp', $product['name']);
$this->assertTrue($product['published']);
$this->assertArrayNotHasKey('deleted_at', $product);
}
}