Skip to content

Instantly share code, notes, and snippets.

@thecrypticace
Last active March 6, 2017 02:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thecrypticace/4a97417fae670ff73f8def414cd8691b to your computer and use it in GitHub Desktop.
Save thecrypticace/4a97417fae670ff73f8def414cd8691b to your computer and use it in GitHub Desktop.
Enhanced version of exception handler replacement
<?php
namespace Tests\Concerns;
use Exception;
use Throwable;
use App\Exceptions\Handler;
use Illuminate\Contracts\Debug\ExceptionHandler;
trait InteractsWithExceptionHandling
{
protected static $exception;
protected function withHandledExceptions()
{
return $this->handleExceptionsUsing(function (Throwable $e) {
return;
});
}
protected function interceptHandledExceptions()
{
return $this->handleExceptionsUsing(function (Throwable $e) {
static::$exception = $e;
});
}
protected function disableExceptionHandling()
{
return $this->handleExceptionsUsing(function (Throwable $e) {
throw $e;
});
}
protected function handleExceptionsUsing($callback)
{
$this->app->instance(ExceptionHandler::class, new class ($this->app, $callback) extends Handler {
public function __construct($container, $callback) {
parent::__construct($container);
$this->callback = $callback;
}
public function render($request, Exception $e) {
($this->callback)($e);
return parent::render($request, $e);
}
});
return $this;
}
/** @before */
protected function clearCachedException()
{
static::$exception = null;
}
protected function onNotSuccessfulTest(Throwable $t)
{
$t = static::$exception ?? $t;
static::$exception = null;
parent::onNotSuccessfulTest($t);
}
}
<?php
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
use Concerns\InteractsWithExceptionHandling;
public function setUp()
{
parent::setUp();
$this->interceptHandledExceptions();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment