如何为某些测试启用 VerifyCsrfToken?

How do I enable VerifyCsrfToken for some tests?

Laravel 默认 disables VerifyCsrfToken 中间件如果 运行 测试。结果我没有注意到 api 路由需要 csrf 令牌才能成功。有没有办法让它恢复一些测试?喜欢

function withVerifyCsrfTokenMiddleware()
{
    $this->app...   // here we're passing something to the app
}

并对VerifyCsrfTokenhandle方法进行修改。在定制的。一个是覆盖框架中的方法。但这只是我的想法。还有更好的吗?

好的,这是我所做的:

app/Http/Middleware/VerifyCsrfToken.php:

function handle($request, Closure $next)
{
    $dontSkipCsrfVerificationWhenRunningTests
        = $this->app->bound('dontSkipCsrfVerificationWhenRunningTests')
            && $this->app->make('dontSkipCsrfVerificationWhenRunningTests');
    if (
        $this->isReading($request) ||
        ! $dontSkipCsrfVerificationWhenRunningTests && $this->runningUnitTests() ||
        $this->shouldPassThrough($request) ||
        $this->tokensMatch($request)
    ) {
        return $this->addCookieToResponse($request, $next($request));
    }

    throw new TokenMismatchException;
}

tests/TestCase.php:

function withVerifyCsrfTokenMiddleware()
{
    $this->app->instance('dontSkipCsrfVerificationWhenRunningTests', TRUE);
}

对上面的答案稍作改动,而不是更改 handle 方法,我更新了 runningUnitTests 方法以减少升级时出现问题的可能性:

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
    ];

    /**
     * Determine if the application is running unit tests.
     *
     * @return bool
     */
    protected function runningUnitTests()
    {
        $dontSkip
        = $this->app->bound('dontSkipCsrfVerificationWhenRunningTests')
        && $this->app->make('dontSkipCsrfVerificationWhenRunningTests');

        return $this->app->runningInConsole() && $this->app->runningUnitTests() && !$dontSkip;
    }
}