暂时禁用/绕过中间件

Temporarily disable / bypass Middleware

在我的应用程序中,我实现了一个 OAuth2-Server (oauth2-server-laravel) in combination with a custom Authentication Package (Sentinel by Cartalyst)。

在我的 routes.php:

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

因此请求必须提供授权 header 否则应用程序将退出并出现 OAuthException。

现在我想对我的控制器进行单元测试。因此,我必须为每个测试使用 OAuth session 和访问令牌来为我的数据库播种。 然后覆盖 TestCasecall()-method 并使用 Bearer Token 设置 HTTP-Authorization Header。

有没有办法禁用或绕过中间件(在我的例子中只是为了单元测试)?

在 Laravel 4 中,它们被称为路由过滤器,并且无论如何在测试环境中被禁用。您也可以使用 Route::enableFilters().

手动 enable/disable 它们

我能想到的唯一答案是在实际的中间件本身中设置一个旁路。例如:

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
}

我不喜欢让中间件依赖于应用程序环境的想法,但我看不到任何其他选项。

这是我遇到同样问题后处理的一个包。

https://github.com/moon0326/FakeMiddleware

显然随着 Laravel 5.1 昨天的发布,一个 disableMiddleware() 方法被添加到 TestCase class,现在它完全符合我的要求。

问题已解决。 :)