dongyigua4468 2015-12-18 13:58
浏览 299
已采纳

如何在Laravel测试中禁用选定的中间件

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

So in the TestCase we use:

use WithoutMiddleware;

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.

  • 写回答

3条回答 默认 最新

  • duangai1941 2015-12-18 14:28
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据