SyntaxStudy
Sign Up
PHP Testing Exception Behavior
PHP Intermediate 5 min read

Testing Exception Behavior

Testing Exceptions in PHPUnit

Use PHPUnit's expectException() and expectExceptionMessage() to assert that code throws the expected exception.

Example
<?php
use PHPUnit\Framework\TestCase;

class UserServiceTest extends TestCase {
    public function test_throws_not_found_exception(): void {
        $service = new UserService($this->createMock(UserRepository::class));

        $this->expectException(NotFoundException::class);
        $this->expectExceptionMessage("User 999 not found");
        $this->expectExceptionCode(404);

        $service->getUser(999);
    }

    public function test_throws_on_invalid_email(): void {
        $this->expectException(ValidationException::class);
        new User("", "not-an-email");
    }
}
Pro Tip

Set expectException() before the code that should throw — PHPUnit marks the test as failed if no exception is thrown.