我正在使用 phpunit 来运行功能测试,但我在使用某些表单时遇到问题。问题是 phpunit 不支持 JS,而我有一个带有动态填充选择框的表单,需要 jQuery。
所以我需要直接传递表单数据。 《书》给出了以下例子:
// Directly submit a form (but using the Crawler is easier!)
$client->request('POST', '/submit', array('name' => 'Fabien'));
当我使用这个示例时,控制器没有收到任何表单数据。最初,我发现在我的情况下传递数组键“名称”是不正确的,因为我需要代码中的表单名称“时间表”。所以我尝试了类似的方法:
$client->request('POST', '/timesheet/create', array('timesheet[project]' => '100'));
但这仍然不起作用。在控制器中,我试图了解发生了什么以及如果收到任何东西会怎样:
$postData = $request->request->get('timesheet');
$project = $postData['project'];
这不起作用,$project 仍然是空的。但是,如果我使用以下代码,我得到的值:
$project = $request->request->get('timesheet[project]');
但显然这不是我想要的。至少我可以看到有一些 POST 数据。我的最后一次尝试是在测试方法中尝试以下操作:
$this->crawler = $this->client->request('POST', '/timesheet/create/', array('timesheet' => array(project => '100'));
因此,我尝试传递“时间表”数组作为请求参数数组的第一个元素。但这样我得到了错误:
Symfony\Component\Form\Exception\UnexpectedTypeException: Expected argument of type "array", "string" given (uncaught exception) at /mnt/hgfs/pmt/src/vendor/symfony/src/Symfony/Component/Form/Form.php line 489
如果有人可以扩展“书”中关于我应该如何使其工作的内容,我将非常高兴。
控制器中的表单绑定:
if ($request->getMethod() == 'POST') {
$form->bindRequest($request);
if ($form->isValid()) {
$postData = $request->request->get('timesheet');
$project = $postData['project'];
$timesheetmanager = $this->get('wlp_pmt.timesheet_db_access');
$timesheetmanager->editTimesheet($timesheet);
return $this->redirect($this->generateUrl('timesheet_list'));
}
}