Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
allows to check toThrow against an exception instance
  • Loading branch information
fabio-ivona committed May 1, 2023
1 parent 2e25eb5 commit f8930d2
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/Mixins/Expectation.php
Expand Up @@ -842,7 +842,7 @@ public function toContainOnlyInstancesOf(string $class, string $message = ''): s
* @param (Closure(Throwable): mixed)|string $exception
* @return self<TValue>
*/
public function toThrow(callable|string $exception, string $exceptionMessage = null, string $message = ''): self
public function toThrow(callable|string|Throwable $exception, string $exceptionMessage = null, string $message = ''): self
{
$callback = NullClosure::create();

Expand All @@ -864,6 +864,15 @@ public function toThrow(callable|string $exception, string $exceptionMessage = n
try {
($this->value)();
} catch (Throwable $e) {

if ($exception instanceof Throwable) {
expect($e)
->toBeInstanceOf($exception::class, $message)
->and($e->getMessage())->toBe($exceptionMessage ?? $exception->getMessage(), $message);

return $this;
}

if (! class_exists($exception)) {
if ($e instanceof Error && $e->getMessage() === "Class \"$exception\" not found") {
Assert::assertTrue(true);
Expand All @@ -888,7 +897,7 @@ public function toThrow(callable|string $exception, string $exceptionMessage = n

Assert::assertTrue(true);

if (! class_exists($exception)) {
if (! $exception instanceof Throwable && ! class_exists($exception)) {
throw new ExpectationFailedException("Exception with message \"$exception\" not thrown.");
}

Expand Down
13 changes: 13 additions & 0 deletions tests/Features/Expect/toThrow.php
Expand Up @@ -2,6 +2,10 @@

use PHPUnit\Framework\ExpectationFailedException;

class CustomException extends Exception
{
}

test('passes', function () {
expect(function () {
throw new RuntimeException();
Expand Down Expand Up @@ -33,6 +37,9 @@
throw new RuntimeException('actual message');
})->toThrow(function (RuntimeException $e) {
}, 'actual message');
expect(function () {
throw new CustomException('foo');
})->toThrow(new CustomException('foo'));
});

test('failures 1', function () {
Expand Down Expand Up @@ -79,6 +86,12 @@
})->toThrow(RuntimeException::class, 'expected message');
})->throws(ExpectationFailedException::class);

test('failures 8', function () {
expect(function () {
throw new CustomException('actual message');
})->toThrow(new CustomException('expected message'));
})->throws(ExpectationFailedException::class);

test('failures with custom message', function () {
expect(function () {
throw new RuntimeException('actual message');
Expand Down

0 comments on commit f8930d2

Please sign in to comment.