Laravel >= 5.5
从 Laravel 5.5 开始,withoutMiddleware() 方法允许您指定要禁用的中间件,而不是全部禁用。因此,无需修改所有中间件以添加环境检查,您可以在测试中执行此操作:
$this->withoutMiddleware(\App\Http\Middleware\VerifyCsrfToken::class);
Laravel
如果您使用的是 Laravel
PHP >= 7
如果您使用的是 PHP7+,请将以下内容添加到您的 TestCase 类中,您将能够使用上述相同的方法调用。此功能使用 PHP7 中引入的匿名类。
/**
* Disable middleware for the test.
*
* @param string|array|null $middleware
* @return $this
*/
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
如果您使用的是 PHP
在某处创建此类:
class FakeMiddleware
{
public function handle($request, $next)
{
return $next($request);
}
}
覆盖TestCase 中的withoutMiddleware() 方法并使用FakeMiddleware 类:
/**
* Disable middleware for the test.
*
* @param string|array|null $middleware
* @return $this
*/
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;
}