Laravel's recent release of Laravel 11.4 introduced the Exceptions facade, which adds conveniences around asserting exceptions in Laravel's exception

Asserting Exceptions in Laravel Tests

submited by
Style Pass
2024-04-18 15:00:03

Laravel's recent release of Laravel 11.4 introduced the Exceptions facade, which adds conveniences around asserting exceptions in Laravel's exception handler. Before this release, I would typically use the $this->withoutExceptionHandling() to assert that a specific exception happened during an HTTP test:

When you expect a request to not throw any exceptions, using withoutExceptionHandling cuts out the middleman when you're debugging why an error is happening when you don't expect it. The above code is tedious to write, because it manually captures the exception, makes assertions about the exception, and calls return to avoid the manual $this->fail() call. The manual failure will catch situations when the test doesn't throw an exception when expected.

Using the Exceptions facade gives us the bonus of not having to capture an exception to assert things manually. Said another way, the test can keep Laravel's exception handler in place but still be able to assert exceptions that happened during a request.

Leave a Comment