Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Phpunit Assert Exception Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

  • Install with Composer: composer require --dev vladahejda/phpunit-assert-exception. It is a test-only dependency; keep it in require-dev.
  • Add the trait to a test class (or better, to your project’s base TestCase):
    use VladaHejda\AssertException;
    
    class PaymentTest extends TestCase
    {
        use AssertException;
    }
    
  • Look first at 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).
  • First use case — replace a 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.

Implementation Patterns

  • Inline “act + assert” tests. Unlike PHPUnit’s 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.
  • Return-value inspection. Use the caught throwable to assert things the method signature does not cover:
    $e = $this->assertException(fn () => $service->run(), DomainException::class);
    $this->assertSame(42, $e->getCode());
    $this->assertInstanceOf(SomeInterface::class, $e->getPrevious());
    
  • Test multiple failure paths in one test. Because the assertion returns rather than registers global state, repeated calls in a single test method or data provider row are safe.
  • Base-class adoption. Put use AssertException; on your tests/TestCase.php so every test has access without boilerplate.
  • Pest projects. Register the trait globally, e.g. uses(\VladaHejda\AssertException::class)->in('tests');, then use the same methods inside test()/it() closures.
  • Choose the right method. 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.

Gotchas and Tips

  • No-throw failures are the common trap. If the callback returns normally the assertion fails, so wrap only code that must throw — preconditions or side effects before the throw can hide the real problem.
  • Message matching is strict. The package compares the thrown message against the string you pass; if you need substring or regex matching, catch the throwable via the returned value and use assertStringContainsString() / assertMatchesRegularExpression() yourself.
  • Parameter ordering with optional args. Passing only a message but wanting to skip code checks requires passing 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).
  • PHPUnit version drift. The trait predates PHPUnit 10’s namespace cleanups; if you are on PHPUnit 10/11, verify the import path and that message assertions have not been deprecated in your version.
  • Debugging failures. If you’re unsure what was thrown, temporarily swap to assertThrowable(..., \Throwable::class) and dump the returned object; the failure message will also tell you whether nothing was thrown or the class/message mismatched.
  • Extension points. Wrap the trait in your own helper assertion (e.g. assertValidationFails()) to standardize class + message pairs across the suite; that is usually cleaner than repeating long argument lists.
  • Prefer native PHPUnit when sufficient. For simple “this call should throw” cases, $this->expectException() is idiomatic; reach for this trait when you need the throwable back, multiple assertions in one test, or inline readability.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
pharaonic/laravel-notification-dependencies
beautinow/translug
dev-brainiac/bot-cloaked
octoberrain/html
octoberrain/extension
octoberrain/exception
octoberrain/contracts
frankyso/ipaymu
3mdikram/worldmoneywords
snowsoft/config
itmosoft/laravel-subscriptions
larva/laravel-ai-qwen
adachsoft/api-version-bundle
cgv/localized-resource
noith/settings
kda/laravel-package
kda/filament-dynamic-navigation
bypersoft/signbox
pairus/product-data
fayne/laravel-filament-cms-core