Last active
September 16, 2017 20:33
-
-
Save stidges/f2587e7e7099f89c50b441415914095a to your computer and use it in GitHub Desktop.
Easily test your Laravel middleware classes. Blog post: http://blog.stidges.com/post/testing-your-laravel-middleware
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\TestResponse; | |
use Illuminate\Foundation\Testing\TestCase as BaseTestCase; | |
use PHPUnit\Framework\Assert; | |
abstract class TestCase extends BaseTestCase | |
{ | |
use CreatesApplication; | |
/** | |
* Setup the test environment. | |
* | |
* @return void | |
*/ | |
protected function setUp() | |
{ | |
parent::setUp(); | |
TestResponse::macro('assertMiddlewarePassed', function () { | |
Assert::assertEquals('__passed__', $this->content()); | |
}); | |
} | |
/** | |
* Call the given middleware. | |
* | |
* @param string|string[] $middleware | |
* @param string $method | |
* @param array $data | |
* @return \Illuminate\Foundation\Testing\TestResponse | |
*/ | |
protected function callMiddleware($middleware, $method = 'GET', array $data = []) | |
{ | |
return $this->call( | |
$method, $this->makeMiddlewareRoute($method, $middleware), $data | |
); | |
} | |
/** | |
* Call the given middleware using a JSON request. | |
* | |
* @param string|string[] $middleware | |
* @param string $method | |
* @param array $data | |
* @return \Illuminate\Foundation\Testing\TestResponse | |
*/ | |
protected function callMiddlewareJson($middleware, $method = 'GET', array $data = []) | |
{ | |
return $this->json( | |
$method, $this->makeMiddlewareRoute($method, $middleware), $data | |
); | |
} | |
/** | |
* Make a dummy route with the given middleware applied. | |
* | |
* @param string $method | |
* @param string|string[] $middleware | |
* @return string | |
*/ | |
protected function makeMiddlewareRoute($method, $middleware) | |
{ | |
$method = strtolower($method); | |
return $this->app->make('router')->{$method}('/__middleware__', [ | |
'middleware' => $middleware, | |
function () { | |
return '__passed__'; | |
} | |
])->uri(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment