Handle exceptions inside a test without a stop!
Assertions for exceptions. Works with PHPUnit and Codeception.
Catch exception thrown inside a code block.
<?php
$this->assertThrows(NotFoundException::class, function() {
$this->userController->show(999);
});
// alternatively
$this->assertThrows(new NotFoundException, function() {
$this->userController->show(999);
});
?>
You can optionally test the exception message:
<?php
$this->assertThrowsWithMessage(NotFoundException::class, 'my error message', function() {
throw new NotFoundException('my error message');
});
?>
composer require codeception/assert-throws --dev
Include AssertThrows
trait it to a TestCase:
<?php
class MyTest extends PHPUnit\Framework\TestCase
{
use Codeception\AssertThrows;
}