Skip to content

Instantly share code, notes, and snippets.

@adamwathan

adamwathan/0.md Secret

Last active February 12, 2022 09:57
Show Gist options
  • Star 39 You must be signed in to star a gist
  • Fork 16 You must be signed in to fork a gist
  • Save adamwathan/c9752f61102dc056d157 to your computer and use it in GitHub Desktop.
Save adamwathan/c9752f61102dc056d157 to your computer and use it in GitHub Desktop.
Disable exception handling in Laravel acceptance tests

Just a quick helper method you can add to your base TestCase to make it easy to toggle exception handling on the fly. Improved a little bit from the sloppier version I used in the screencast :)

Update 2016-11-09:

At some point since I originally shared this snippet and the accompanying screencast, Laravel started binding App\Exceptions\Handler under the Illuminate\Contracts\Debug\ExceptionHandler interface instead of the concrete class, so I've updated the files below to account for that.

<?php
use App\Exceptions\Handler;
use Illuminate\Contracts\Debug\ExceptionHandler;
class TestCase extends Illuminate\Foundation\Testing\TestCase
{
// Framework-supplied test case methods snipped for brevity
// Use this version if you're on PHP 7
protected function disableExceptionHandling()
{
$this->app->instance(ExceptionHandler::class, new class extends Handler {
public function __construct() {}
public function report(Exception $e)
{
// no-op
}
public function render($request, Exception $e) {
throw $e;
}
});
}
}
<?php
use App\Exceptions\Handler;
use Illuminate\Contracts\Debug\ExceptionHandler;
class TestCase extends Illuminate\Foundation\Testing\TestCase
{
// Framework-supplied test case methods snipped for brevity
// Use this version if you're on PHP 5
protected function disableExceptionHandling()
{
app()->instance(ExceptionHandler::class, new PassThroughHandler);
}
}
class PassThroughHandler extends Handler
{
public function __construct() {}
public function report(Exception $e)
{
// no-op
}
public function render($request, Exception $e)
{
throw $e;
}
}
@michielgerritsen
Copy link

Thanks for this snippet, it makes the error in some cases way more verbose. There is only 1 but: You need to import the Exception namespace as it will throw an error that it is not compatible with the parent ExceptionHandler.

@vrajroham
Copy link

Thanks for snippet. Awesome 🎉

@amadeann
Copy link

If you come here from Google for the snippet featured in lesson 8 of Laracasts series on 'Forum TDD', you are looking for this gist: https://gist.github.com/adamwathan/125847c7e3f16b88fa33a9f8b42333da

@stefnats
Copy link

I made some extensions to this very useful code here:

https://gist.github.com/stefnats/5c68a77aa17c50903af29dfcafde1b0a

It prevents throwing exceptions on common errors like ValidationException or NotFoundException

@jkirira
Copy link

jkirira commented Feb 12, 2022

@amadeann Thanks man.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment