为什么我在 Laravel 中运行测试时收到“CSRF 令牌不匹配”?

Mih*_*iță 9 phpunit csrf laravel

我想在不收到“CSRF 令牌不匹配”异常的情况下运行我的测试。在 laravel 文档中指出:

运行测试时,CSRF 中间件会自动禁用。

抛出异常的代码行如下所示:

$response = $this->json('POST', route('order.create'), [
     'product_id', $product->id
]);
Run Code Online (Sandbox Code Playgroud)

为了运行测试,我在我的 zsh 终端中工作:

php artisan test --env=testing
Run Code Online (Sandbox Code Playgroud)

这是我的测试课:

<?php

   namespace Tests\Feature;

   use Illuminate\Foundation\Testing\RefreshDatabase;
   use Illuminate\Foundation\Testing\WithFaker;
   use Illuminate\Foundation\Testing\WithoutMiddleware;
   use Tests\TestCase;

  class SessionCartTest extends TestCase
  {
      public function testExample()
      {
          $product = \App\Product::inRandomOrder()->first();
          $response = $this->postJson(route('order.insert'), [
              'product_id' => $product->id,
          ]);
          $response->assertStatus(200); // here I receive 419
      }
  }
Run Code Online (Sandbox Code Playgroud)

我做错了什么,我该如何解决?我正在使用 Laravel 7。

Dan*_*atz 26

我现在遇到这个问题 x 次,每次我通过运行来修复它: php artisan config:clear

  • 我需要制作一个杯子,上面写着这个或其他东西。很多次我发现了一些非常奇怪的行为,这已经解决了它。 (3认同)

Dio*_*mes 7

可能APP_ENV未设置为testing

您可以通过在 php 命令之前在命令行中设置 ENV 变量。

因此,在您的情况下,将环境设置为测试并通过以下方式运行 artisan 命令:

APP_ENV=testing php artisan test
Run Code Online (Sandbox Code Playgroud)