Last active
March 6, 2017 02:27
-
-
Save thecrypticace/4a97417fae670ff73f8def414cd8691b to your computer and use it in GitHub Desktop.
Enhanced version of exception handler replacement
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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