SyntaxStudy
Sign Up
PHP Testing Exceptions
PHP Beginner 3 min read

Testing Exceptions

Exception Testing

Test that exceptions are thrown at the right time with the right message and type.

Example
// PHPUnit
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage("Age must be positive");
$this->expectExceptionCode(422);
createUser(["age" => -1]);
// Pest
expect(fn() => createUser(["age" => -1]))
    ->toThrow(InvalidArgumentException::class, "Age must be positive");
// Assert no exception
$this->expectNotToPerformAssertions();
createUser(["age" => 25]);
Pro Tip

expectException must be called before the code that throws — it does not catch retroactively.