如何在Laravel测试中禁用选定的中间件 [英] How to Disable Selected Middleware in Laravel Tests
问题描述
因此,通常在运行phpunit
时会出现来自身份验证和CSRF的错误.
So it is common that errors from Authentication and CSRF arise when running phpunit
.
因此在TestCase中,我们使用:
So in the TestCase we use:
use WithoutMiddleware;
问题是当表单失败时,它通常会返回一条Flash消息和一个旧输入.我们已禁用所有中间件,因此我们无法访问Input::old('username');
或Flash消息.
The problem with this is that when forms fail, it usually comes back with a Flash Message and Old Input. We have disabled all middleware so we have no access to Input::old('username');
or the flash message.
此外,我们对此失败的表单发布的测试返回:
Furthermore our tests of this failed form post returns:
Caused by
exception 'RuntimeException' with message 'Session store not set on request.
有没有一种方法可以启用会话中间件并禁用其他所有功能.
Is there a way to enable the Session Middleware and disable everything else.
推荐答案
我发现做到这一点的最佳方法不是通过使用WithoutMiddleware
特性,而是通过修改要禁用的中间件.例如,如果要在测试中禁用VerifyCsrfToken
中间件功能,则可以执行以下操作.
The best way I have found to do this isn't by using the WithoutMiddleware
trait but by modifying the middleware you want to disable. For example, if you want to disable the VerifyCsrfToken
middleware functionality in your tests you can do the following.
在app/Http/Middleware/VerifyCsrfToken.php
内,添加用于检查APP_ENV
进行测试的handle
方法.
Inside app/Http/Middleware/VerifyCsrfToken.php
, add a handle
method that checks the APP_ENV
for testing.
public function handle($request, Closure $next)
{
if (env('APP_ENV') === 'testing') {
return $next($request);
}
return parent::handle($request, $next);
}
这将覆盖Illuminate\Foundation\Http\Middleware\VerifyCsrfToken
内部的handle
方法,从而完全禁用该功能.
This will override the handle
method inside of Illuminate\Foundation\Http\Middleware\VerifyCsrfToken
, disabling the functionality entirely.
这篇关于如何在Laravel测试中禁用选定的中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!