[英]PHPUnit POST request not sending parameters with Symfony2
I am writing a Symfony2 PHPUnit functional test to test a form page. 我正在编写一个Symfony2 PHPUnit功能测试来测试表单页面。 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. 在测试中,我试图创建一个包含表单参数的POST请求,将其发送到createAction,然后断言页面已重新路由。 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. var_dump输出是一个空数组。 However if I change my request method to a GET, 但是,如果我将请求方法更改为GET,
$client->request('GET', '/create/adviseeSet', array(
'name' => 'Monkey Hour',
'advisor' => '523',
'day' => 'Monday',
'year' => '20'
),
array()
);
And var_dump the request's query 和var_dump请求的查询
$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? 如何获得POST请求以使其在GET请求中也能正常执行?
If you are writing functional tests you should always check html output like this var_dump($client->getResponse()->getContent())
; 如果您正在编写功能测试,则应始终检查html输出,例如var_dump($client->getResponse()->getContent())
; . 。
Maybe you have forgotten to add csrf token. 也许您忘记了添加csrf令牌。 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',
));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.