我正在使用phpunit来运行功能测试,但我遇到了一些问题.问题是phpunit不知道JS,我有一个表单,其中包含一个需要jQuery的动态填充选择框.
所以我需要直接传递表单数据.'book'给出了以下示例:
// Directly submit a form (but using the Crawler is easier!)
$client->request('POST', '/submit', array('name' => 'Fabien'));
Run Code Online (Sandbox Code Playgroud)
当我使用这个例子时,控制器没有收到任何表单数据.最初我看到传递数组键'name'在我的情况下不正确,因为我需要在我的代码中使用'timesheet'的表单名称.所以我尝试了类似的东西:
$client->request('POST', '/timesheet/create', array('timesheet[project]' => '100'));
Run Code Online (Sandbox Code Playgroud)
但这仍然无效.在控制器中,我试图了解发生了什么以及如果收到了什么:
$postData = $request->request->get('timesheet');
$project = $postData['project'];
Run Code Online (Sandbox Code Playgroud)
这不起作用,$ project仍然是空的.但是,如果我使用以下代码,我得到了值:
$project = $request->request->get('timesheet[project]');
Run Code Online (Sandbox Code Playgroud)
但显然这不是我想要的.至少虽然我可以看到有一些POST数据.我的最后一次尝试是在测试方法中尝试以下方法:
$this->crawler = $this->client->request('POST', '/timesheet/create/', array('timesheet' => array(project => '100'));
Run Code Online (Sandbox Code Playgroud)
所以我试图传递'timesheet'数组作为请求参数数组的第一个元素.但有了这个我得到错误:
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
Run Code Online (Sandbox Code Playgroud)
如果有人可以扩展"书"中有关我应该如何工作的内容,我将非常高兴.
控制器中的表单绑定:
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'));
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
如果您想知道如何使用测试客户端注入POST数据数组...
在你的测试方法中,做一些类似的事情
$crawler = $client->request('POST', '/foo', array(
'animal_sounds' => array(
'cow' => 'moo',
'duck' => 'quack'
)
); // This would encode to '/foo?animal_sounds%5Bcow%5D=moo&animal_sounds%5Bduck%5D=quack'
$this->assertTrue( ... );
Run Code Online (Sandbox Code Playgroud)
在控制器中,您可以像这样访问您的参数:
$data = $request->request->get('animal_sounds');
$cowNoise = $data['cow'];
$duckNoise = $data['duck'];
Run Code Online (Sandbox Code Playgroud)
或者,如果测试方法是注入有效的表单数据,您可以使用表单API ...
| 归档时间: |
|
| 查看次数: |
8609 次 |
| 最近记录: |