diff --git a/src/Mixins/Expectation.php b/src/Mixins/Expectation.php index 3fbd2110..5823d61c 100644 --- a/src/Mixins/Expectation.php +++ b/src/Mixins/Expectation.php @@ -6,6 +6,7 @@ namespace Pest\Mixins; use BadMethodCallException; use Closure; +use Error; use InvalidArgumentException; use Pest\Exceptions\InvalidExpectationValue; use Pest\Support\Arr; @@ -822,8 +823,12 @@ final class Expectation try { ($this->value)(); - } catch (Throwable $e) { // @phpstan-ignore-line + } catch (Throwable $e) { if (!class_exists($exception)) { + if ($e instanceof Error && $e->getMessage() === "Class \"$exception\" not found") { + throw $e; + } + Assert::assertStringContainsString($exception, $e->getMessage()); return $this; diff --git a/tests/Features/Expect/toThrow.php b/tests/Features/Expect/toThrow.php index 434ced44..b5c66abf 100644 --- a/tests/Features/Expect/toThrow.php +++ b/tests/Features/Expect/toThrow.php @@ -58,3 +58,19 @@ test('closure missing parameter', function () { test('closure missing type-hint', function () { expect(function () {})->toThrow(function ($e) {}); })->throws(InvalidArgumentException::class, 'The given closure\'s parameter must be type-hinted as the class string.'); + +it('can handle a non-defined exception', function () { + expect(function () { + throw new NonExistingException(); + })->toThrow(NonExistingException::class); +})->throws(Error::class, 'Class "NonExistingException" not found'); + +it('can handle a class not found Error', function () { + expect(function () { + throw new NonExistingException(); + })->toThrow('Class "NonExistingException" not found'); + + expect(function () { + throw new NonExistingException(); + })->toThrow(Error::class, 'Class "NonExistingException" not found'); +});