Skip to content

Commit 01b1450

Browse files
[12.x] assertThrowsNothing (#55100)
* assertThrowsNothing * formatting --------- Co-authored-by: Taylor Otwell <[email protected]>
1 parent 203503c commit 01b1450

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

src/Illuminate/Foundation/Testing/Concerns/InteractsWithExceptionHandling.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,4 +213,31 @@ protected function assertThrows(Closure $test, string|Closure $expectedClass = T
213213

214214
return $this;
215215
}
216+
217+
/**
218+
* Assert that the given callback does not throw an exception.
219+
*
220+
* @param \Closure $test
221+
* @return $this
222+
*/
223+
protected function assertDoesntThrow(Closure $test)
224+
{
225+
try {
226+
$test();
227+
228+
$thrown = false;
229+
} catch (Throwable $exception) {
230+
$thrown = true;
231+
232+
$exceptionClass = get_class($exception);
233+
$exceptionMessage = $exception->getMessage();
234+
}
235+
236+
Assert::assertTrue(
237+
! $thrown,
238+
sprintf('Unexpected exception of type %s with message %s was thrown.', $exceptionClass ?? null, $exceptionMessage ?? null)
239+
);
240+
241+
return $this;
242+
}
216243
}

tests/Foundation/FoundationExceptionsHandlerTest.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -571,6 +571,35 @@ public function testAssertExceptionIsThrown()
571571
}
572572
}
573573

574+
public function testAssertNoExceptionIsThrown()
575+
{
576+
try {
577+
$this->assertDoesntThrow(function () {
578+
throw new Exception;
579+
});
580+
581+
$testFailed = true;
582+
} catch (AssertionFailedError) {
583+
$testFailed = false;
584+
}
585+
586+
if ($testFailed) {
587+
Assert::fail('assertDoesntThrow failed: thrown exception was not detected.');
588+
}
589+
590+
try {
591+
$this->assertDoesntThrow(function () { });
592+
593+
$testFailed = false;
594+
} catch (AssertionFailedError) {
595+
$testFailed = true;
596+
}
597+
598+
if ($testFailed) {
599+
Assert::fail('assertDoesntThrow failed: exception was detected while no exception was thrown.');
600+
}
601+
}
602+
574603
public function testItReportsDuplicateExceptions()
575604
{
576605
$reported = [];

0 commit comments

Comments
 (0)