【问题标题】:Symfony 4 Functional Form Test with CSRF Token and Session带有 CSRF 令牌和会话的 Symfony 4 功能形式测试
【发布时间】:2021-02-24 12:10:48
【问题描述】:

我正在使用带有表单包的 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

【问题讨论】:

    标签: php symfony session phpunit functional-testing


    【解决方案1】:

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

    // 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());
    

    【讨论】:

    • 您好,感谢您的回答,但这是我以前的方式。如果我将 .env.local 更改为 env test 并在前端查看它,它也不起作用。所以测试环境一定有一些缺失/错误。
    猜你喜欢
    • 2019-06-11
    • 2014-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-26
    • 2015-01-04
    • 2020-02-10
    • 2011-01-19
    相关资源
    最近更新 更多