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',
            ));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵