Assertions Reference
5 min read Quiz at the end
Reference for assertEquals, assertSame, assertNull, assertCount, assertContains, and assertInstanceOf.
PHPUnit Assertions
// Equality
$this->assertEquals(5, $result); // loose equality
$this->assertSame(5, $result); // strict (===)
$this->assertNotEquals(5, $result);
// Truthiness
$this->assertTrue($condition);
$this->assertFalse($condition);
$this->assertNull($value);
$this->assertNotNull($value);
// Types
$this->assertIsInt($value);
$this->assertIsString($value);
$this->assertIsArray($value);
$this->assertInstanceOf(User::class, $user);
// Arrays
$this->assertCount(3, $array);
$this->assertContains("item", $array);
$this->assertArrayHasKey("name", $array);
$this->assertArrayNotHasKey("password", $response);
// Strings
$this->assertStringContainsString("hello", $str);
$this->assertStringStartsWith("Hello", $str);
$this->assertMatchesRegularExpression("/^d+$/", $str);
// Exceptions
$this->expectException(RuntimeException::class);
$this->expectExceptionCode(404);
$this->expectExceptionMessage("Not found")
Topic Quiz · 3 questions
Test your understanding before moving on
1. Which assertion uses strict === comparison?
💡 assertSame() uses strict type-safe comparison (===); assertEquals() is loose (==).
2. Which assertion checks object class type?
💡 assertInstanceOf(ClassName::class, $object) checks the object type.
3. Which assertion checks a string contains a substring?
💡 assertStringContainsString($needle, $haystack) checks substring presence.