使用CSRF令牌和会话的Symfony 4功能形式测试

问题描述

我正在使用带有捆绑软件的symfony 4.4,并希望进行一些功能测试。

我的表单有多个步骤,我想执行一个完整的表单直到成功消息。但是使用csrf_protection:true我什至无法进入第2页。如果在测试环境中将其禁用,则可以进入第2页。如果在第2页转储会话,则可以看到它是空的。这是我的测试示例:

$client = static::createClient();
$client->request('GET','/test');
$crawler = $client->submitForm('Next',['name' => 'Max Mustermann']); // => lands on step2
$crawler = $client->submitForm('Next',['email' => 'asdf@ase.de']); // => lands back on step 1 with emtpy form. So session is empty

有人知道这里有什么问题吗? 此页面说,那是必须的,但事实并非如此。 https://symfony.com/doc/4.4/components/http_foundation/session_testing.html#functional-testing

解决方法

我建议您从客户的响应中检索表单,然后将表单和数据一起提交,例如:

// Get the crawler
$crawler = $client->request('GET','/test');

// Get the form
$form = $crawler->filter('form')->form();

// Fill the form. NB: double check your form structure/fields name
$form['name'] = 'Max Mustermann';
$form['email'] = 'asdf@ase.de';

// Submit the form.
$crawler = $this->client->submit($form);
$this->assertEquals(200,$this->client->getResponse()->getStatusCode());