Exception Testing
Test that exceptions are thrown at the right time with the right message and type.
Test that exceptions are thrown at the right time with the right message and type.
// 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]);
expectException must be called before the code that throws — it does not catch retroactively.