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 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)