vladahejda/phpunit-assert-exception
A PHPUnit helper that adds an assertException() assertion for testing exceptions thrown inside callbacks. Specify the expected exception class, message, and code in one concise call, reducing boilerplate and making exception tests clearer in PHP projects.
composer require --dev vladahejda/phpunit-assert-exception. It is a test-only dependency; keep it in require-dev.TestCase):
use VladaHejda\AssertException;
class PaymentTest extends TestCase
{
use AssertException;
}
src/AssertException.php and the README. The public surface is small: assertException(), assertThrowable(), and assertError() (the latter two are the PHP 7+ escape hatches for Throwable/Error).try/catch around a call that should blow up, with an inline assertion:
$this->assertException(
fn () => $gateway->charge($card),
PaymentFailedException::class,
'Card declined'
);
The callback is invoked immediately, the throwable is caught, and the assertion fails if nothing is thrown or the wrong type/message is raised.expectException(), which is only declared before the call and only allows one exception per test, the trait lets you write call-and-assert in a single expression and mix it with other assertions.$e = $this->assertException(fn () => $service->run(), DomainException::class);
$this->assertSame(42, $e->getCode());
$this->assertInstanceOf(SomeInterface::class, $e->getPrevious());
use AssertException; on your tests/TestCase.php so every test has access without boilerplate.uses(\VladaHejda\AssertException::class)->in('tests');, then use the same methods inside test()/it() closures.assertException() is for Exception hierarchies (PHP 5-compatible path); assertThrowable() for anything implementing Throwable; assertError() for Error/TypeError/AssertionError cases. Matching the narrowest appropriate method keeps failure messages meaningful.assertStringContainsString() / assertMatchesRegularExpression() yourself.null for the skipped slot; double-check the signature in the source before relying on positional arguments.Exception vs Error. assertException() will not satisfy an Error thrown inside the callback; use assertThrowable() or assertError() when testing PHP 7+ error conditions (e.g. TypeError from a type declaration).assertThrowable(..., \Throwable::class) and dump the returned object; the failure message will also tell you whether nothing was thrown or the class/message mismatched.assertValidationFails()) to standardize class + message pairs across the suite; that is usually cleaner than repeating long argument lists.$this->expectException() is idiomatic; reach for this trait when you need the throwable back, multiple assertions in one test, or inline readability.How can I help you explore Laravel packages today?