Laravel >= 5.5
从 Laravel 5.5 开始,withoutMiddleware()
方法允许你指定要禁用的中间件,而不是禁用所有中间件。因此,你可以在测试中执行以下操作,而无需修改所有中间件以添加 env 检查:
$this->withoutMiddleware(\App\Http\Middleware\VerifyCsrfToken::class);
Laravel < 5.5
如果您使用的是 Laravel < 5.5 版本,您可以将更新方法添加到基础 TestCase 类中以覆盖框架 TestCase 的功能,从而实现相同的功能。
PHP >= 7
如果您使用的是 PHP7+ 版本,则在 TestCase 类中添加以下内容,即可使用上述提到的相同方法调用。此功能使用了 PHP7 中引入的匿名类。
public function withoutMiddleware($middleware = null)
{
if (is_null($middleware)) {
$this->app->instance('middleware.disable', true);
return $this;
}
foreach ((array) $middleware as $abstract) {
$this->app->instance($abstract, new class {
public function handle($request, $next)
{
return $next($request);
}
});
}
return $this;
}
PHP < 7
如果你使用的是 PHP < 7,你需要创建一个真正的类文件,并将其注入容器而不是匿名类。
在某个地方创建这个类:
class FakeMiddleware
{
public function handle($request, $next)
{
return $next($request);
}
}
在您的TestCase
中覆盖withoutMiddleware()
方法并使用您的FakeMiddleware
类:
public function withoutMiddleware($middleware = null)
{
if (is_null($middleware)) {
$this->app->instance('middleware.disable', true);
return $this;
}
foreach ((array) $middleware as $abstract) {
$this->app->instance($abstract, new FakeMiddleware());
}
return $this;
}