Skip to content

[12.x] assertThrowsNothing #55100

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 22, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -213,4 +213,31 @@ protected function assertThrows(Closure $test, string|Closure $expectedClass = T

return $this;
}

/**
* Assert that the given callback does not throw an exception.
*
* @param \Closure $test
* @return $this
*/
protected function assertDoesntThrow(Closure $test)
{
try {
$test();

$thrown = false;
} catch (Throwable $exception) {
$thrown = true;

$exceptionClass = get_class($exception);
$exceptionMessage = $exception->getMessage();
}

Assert::assertTrue(
! $thrown,
sprintf('Unexpected exception of type %s with message %s was thrown.', $exceptionClass ?? null, $exceptionMessage ?? null)
);

return $this;
}
}
29 changes: 29 additions & 0 deletions tests/Foundation/FoundationExceptionsHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -571,6 +571,35 @@ public function testAssertExceptionIsThrown()
}
}

public function testAssertNoExceptionIsThrown()
{
try {
$this->assertDoesntThrow(function () {
throw new Exception;
});

$testFailed = true;
} catch (AssertionFailedError) {
$testFailed = false;
}

if ($testFailed) {
Assert::fail('assertDoesntThrow failed: thrown exception was not detected.');
}

try {
$this->assertDoesntThrow(function () { });

$testFailed = false;
} catch (AssertionFailedError) {
$testFailed = true;
}

if ($testFailed) {
Assert::fail('assertDoesntThrow failed: exception was detected while no exception was thrown.');
}
}

public function testItReportsDuplicateExceptions()
{
$reported = [];
Expand Down
Loading