Test exception throwing with expectException(), expectExceptionMessage(), and expectExceptionCode().
Testing Exceptions
class ExceptionTest extends TestCase {
// Basic exception testing
public function testThrowsException(): void {
$this->expectException(InvalidArgumentException::class);
(new Validator)->validate("");
}
// With message
public function testExceptionMessage(): void {
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage("File not found");
(new FileLoader)->load("missing.txt");
}
// With code
public function testExceptionCode(): void {
$this->expectException(HttpException::class);
$this->expectExceptionCode(404);
(new ApiClient)->get("/missing");
}
// Test exception is NOT thrown
public function testNoExceptionForValidInput(): void {
$this->expectNotToPerformAssertions();
// Just run code — if exception thrown, test fails
(new Validator)->validate("valid input");
}
// Using try/catch for more control
public function testCatchesAndWrapsException(): void {
try {
(new Service)->riskyOperation();
$this->fail("Expected exception was not thrown");
} catch (ServiceException $e) {
$this->assertInstanceOf(RuntimeException::class, $e->getPrevious());
}
}
}