6

In my Application I implemented a OAuth2-Server (oauth2-server-laravel) in combination with a custom Authentication Package (Sentinel by Cartalyst).

In my routes.php:

Route::group(['before' => 'oauth'], function()
{
    // ... some routes here
}

So the request must provide an authorization header or the application quits with an OAuthException.

Now I want to unittest my controllers. So I have to seed my database with a OAuth session and access token for every test. Then overwrite the call()-method of TestCase and set the HTTP-Authorization Header with the Bearer Token.

Is there a way to disable or bypass middleware (in my case just for unit testing)?

In Laravel 4 they were called route filters and they were disabled in the testing environment anyway. You could also manually enable/disable them with Route::enableFilters().

rookian
  • 1,045
  • 14
  • 38
  • I would also like to know the answer to this, my reading so far is that it's not possible to disable middleware in Laravel 5 the way that route filters were disabled in testing mode in Laravel 4. However I'm keen to be proven wrong. – delatbabel Apr 07 '15 at 10:13

3 Answers3

7

Apparently with the release of Laravel 5.1 yesterday a disableMiddleware() method was added to the TestCase class, which now does exactly what I wanted.

Problem solved. :)

rookian
  • 1,045
  • 14
  • 38
  • 3
    So just put `use WithoutMiddleware;` in your test case class – tread Dec 18 '15 at 16:16
  • 1
    An improvement on this has been merged to framework that allows to disable a specific set of middlewares. see https://github.com/laravel/framework/pull/18673 – meysam Apr 28 '17 at 09:48
2

The only answer that I could come up with was to put a bypass in the actual middleware itself. For example:

public function handle($request, Closure $next)
{
    // Don't validate authentication when testing.
    if (env('APP_ENV') === 'testing') {
        return $next($request);
    }
    // ... continue on to process the request
}

I don't like the idea of making the middleware dependent on the app environment but I couldn't see any other options.

delatbabel
  • 3,601
  • 24
  • 29
0

Here's a package that I worked on after having the same issue.

https://github.com/moon0326/FakeMiddleware

Moon
  • 22,195
  • 68
  • 188
  • 269