【发布时间】:2026-02-19 12:30:01
【问题描述】:
我正在尝试在 Symfony2 中测试 ajax 请求。我正在编写一个单元测试,它在我的app/logs/test.log 中引发以下错误:
request.CRITICAL: Uncaught PHP Exception Twig_Error_Runtime:
"Impossible to access an attribute ("0") on a string variable
("The CSRF token is invalid. Please try to resubmit the form.")
in .../vendor/twig/twig/lib/Twig/Template.php:388
我的代码相当简单。
public function testAjaxJsonResponse()
{
$form['post']['title'] = 'test title';
$form['post']['content'] = 'test content';
$form['post']['_token'] = $client->getContainer()->get('form.csrf_provider')->generateCsrfToken();
$client->request('POST', '/path/to/ajax/', $form, array(), array(
'HTTP_X-Requested-With' => 'XMLHttpRequest',
));
$response = $client->getResponse();
$this->assertSame(200, $client->getResponse()->getStatusCode());
$this->assertSame('application/json', $response->headers->get('Content-Type'));
}
问题似乎是CSRF 令牌,我可以为测试禁用它,但我真的不想这样做,我通过发出 2 个请求让它工作(第一个使用表单,我们抓取_token 并使用XMLHttpRequest 发出第二个请求) - 这显然看起来相当愚蠢和低效!
【问题讨论】: