📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PHPUnit Testing Testing Exceptions

Testing Exceptions

5 min read Quiz at the end
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());
        }
    }
}
Topic Quiz · 2 questions

Test your understanding before moving on

1. What does expectException() do when placed before throwing code?
💡 expectException() must come before the throwing code.
2. What does $this->fail() do inside a test?
💡 $this->fail("message") immediately fails the test.