【发布时间】:2020-07-21 17:40:23
【问题描述】:
我想在不收到“CSRF 令牌不匹配”异常的情况下运行我的测试。在 laravel 文档中指出:
运行测试时自动禁用 CSRF 中间件。
抛出异常的代码行如下所示:
$response = $this->json('POST', route('order.create'), [
'product_id', $product->id
]);
为了运行测试,我正在我的 zsh 终端中工作:
php artisan test --env=testing
这是我的测试课:
<?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
}
}
我做错了什么,我该如何解决这个问题?我正在使用 laravel 7。
【问题讨论】:
-
为什么要使用 artisan 命令来运行测试?在控制台上运行 phpunit 会发生什么?你确定你得到了一个 CSRF 异常吗?
-
运行phpunit时也是一样。我正在转储响应,我看到里面有什么,HTTP 错误代码也是 419。
-
你能包含你的测试类吗?
-
@DigitalDrifter 我在问题中添加了我的测试类
-
在 Illuminate\Foundation\Http\Middleware\VerifyCsrfToken 构造函数中以某种方式将 $app->env 设置为“本地”而不是“测试”