Skip to content

Instantly share code, notes, and snippets.

@stidges
Last active September 16, 2017 20:33
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 stidges/f2587e7e7099f89c50b441415914095a to your computer and use it in GitHub Desktop.
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
<?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