How to Disable Selected Middleware in Laravel Tests

前端 未结 4 1379
心在旅途
心在旅途 2020-12-30 03:39

So it is common that errors from Authentication and CSRF arise when running phpunit.

So in the TestCase we use:

use WithoutMiddleware;

4条回答
  •  醉酒成梦
    2020-12-30 04:25

    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.

    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);
    }
    

    This will override the handle method inside of Illuminate\Foundation\Http\Middleware\VerifyCsrfToken, disabling the functionality entirely.

提交回复
热议问题