我正在编写一个Symfony2 PHPUnit功能测试来测试表单页面。在测试中,我试图创建一个包含表单参数的POST请求,将它们发送到createAction,并断言页面重新路由。问题是我的控制器没有收到请求参数。我的测试是:
$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());
控制器操作开始如下:
public function createAction(Request $request) {
$params = $request->request->all();
var_dump($params);
// create entity and reroute user
}
var_dump输出是一个空数组。但是,如果我将请求方法更改为GET,
$client->request('GET', '/create/adviseeSet', array(
'name' => 'Monkey Hour',
'advisor' => '523',
'day' => 'Monday',
'year' => '20'
),
array()
);
并且var_dump请求的查询
$params = $request->query->all();
我看到了我的参数!
array(4) {
["advisor"]=>
string(3) "523"
["day"]=>
string(6) "Monday"
["name"]=>
string(11) "Monkey Hour"
["year"]=>
string(2) "20"
}
如何在GET请求中获取POST请求?
答案 0 :(得分:1)
如果您正在编写功能测试,则应始终检查html输出,如var_dump($client->getResponse()->getContent())
; 。
也许你忘了添加csrf令牌。这是一个例子:
$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(...);
不要忘记在表单类型中添加意图:
$resolver->setDefaults(array(
//some params
'intention' => 'form_intention',
));