dongnao9525 2014-08-20 19:32
浏览 62
已采纳

PHPUnit POST请求不使用Symfony2发送参数

I am writing a Symfony2 PHPUnit functional test to test a form page. In the test I am attempting to create a POST request containing form parameters, send them to a createAction, and assert that the page rerouted. The problem is that my controller is not receiving the request parameters. My test is:

$client = static::createClient();
$client->followRedirects();

$client->request('POST', '/create/adviseeSet', array(
        'name' => 'Monkey Hour',
        'advisor' => '523',
        'day' => 'Monday',
        'year' => '20'
    ),
    array()
);

$this->assertTrue($client->getResponse()->isRedirect());

The controller action begins as follows:

public function createAction(Request $request) {
    $params = $request->request->all();
    var_dump($params);
    // create entity and reroute user
}

The var_dump output is an empty array. However if I change my request method to a GET,

$client->request('GET', '/create/adviseeSet', array(
        'name' => 'Monkey Hour',
        'advisor' => '523',
        'day' => 'Monday',
        'year' => '20'
    ),
    array()
);

And var_dump the request's query

$params = $request->query->all();

I see my parameters!

   array(4) {
     ["advisor"]=>
   string(3) "523"
     ["day"]=>
   string(6) "Monday"
     ["name"]=>
   string(11) "Monkey Hour"
     ["year"]=>
   string(2) "20"
   }

How can I get my POST Request to perform as well at the GET request?

  • 写回答

1条回答 默认 最新

  • dongshi1215 2014-08-22 15:43
    关注

    If you are writing functional tests you should always check html output like this var_dump($client->getResponse()->getContent()); .
    Maybe you have forgotten to add csrf token. Here is example:

    $csrfToken = $client->getContainer()->get('form.csrf_provider')
         ->generateCsrfToken('form_intention');
    
    $client->request('POST', '/create/adviseeSet', array(
        'name' => 'Monkey Hour',
        'advisor' => '523',
        'day' => 'Monday',
        'year' => '20',
        '_token' => $csrfToken
        )
    );
    
    $crawler = $client->followRedirect();
    
    $this->assertTrue(...);
    

    Don't forget to add intention in your form type:

    $resolver->setDefaults(array(
                //some params 
                'intention' => 'form_intention',
            ));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥66 定制开发肯德基自动化网站下单软件
  • ¥20 vscode虚拟环境依赖包未安装
  • ¥15 odoo17关于owl开发js代码问题
  • ¥15 光纤中多普勒频移公式的推导
  • ¥15 怎么制作一个人脸识别门禁系统
  • ¥20 大华dss监控平台网络关闭登不进去
  • ¥15 请使用蚁群算法解决下列问题,并给出我完整的代码
  • ¥20 关于php录入完成后,批量更新数据库
  • ¥15 请教往复密封润滑问题
  • ¥15 cocos creator发布ios包