我目前正在使用Symfony2,并且正在用PHPUnit测试我的项目。 我想用错误的参数提交表单或者URL不完整时测试异常。用symfony2和phpunit修改表单动作
我去了通过Symfony2和PHPUnit的文档,但没有找到任何类/方法来这样做。
如何更改表单动作的值?我想使用PHPUnit,所以创建的报告是最新的,我可以看到我的代码的覆盖范围。
编辑:
为了澄清我的问题,一些新的内容。 如何在我的控制器中测试以'>'开头的行? (throw $this->createNotFoundException('Unable to find ParkingZone entity.');
)
当用户修改操作链接时,控制器中的进程将通过异常(或错误消息,如果选择此操作)。我如何测试这种情况?
控制器
/**
* Edits an existing ParkingZone entity.
*
* @Route("/{id}/update", name="parkingzone_update")
* @Method("post")
* @Template("RatpGarageL1Bundle:ParkingZone:edit.html.twig")
*/
public function updateAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('RatpGarageL1Bundle:ParkingZone')->find($id);
if (!$entity) {
> throw $this->createNotFoundException('Unable to find ParkingZone entity.');
}
$editForm = $this->createForm(new ParkingZoneType(), $entity);
$deleteForm = $this->createDeleteForm($id);
$request = $this->getRequest();
$editForm->bindRequest($request);
if ($editForm->isValid()) {
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('parkingzone_edit', array('id' => $id)));
}
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
检视:
<form action="{{ path('parkingzone_update', { 'id': entity.id }) }}" method="post" {{ form_enctype(form) }}>
<div class="control-group">
{{ form_label(form.name, 'Name', { 'attr': {'class': 'control-label'} }) }}
<div class="controls error">
{{ form_widget(form.name, { 'attr': {'class': ''} }) }}
<span class="help-inline">{{ form_errors(form.name) }}</span>
</div>
</div>
<div class="control-group">
{{ form_label(form.orderSequence, 'Rang', { 'attr': {'class': 'control-label'} }) }}
<div class="controls error">
{{ form_widget(form.orderSequence, { 'attr': {'class': ''} }) }}
<span class="help-inline">{{ form_errors(form.orderSequence) }}</span>
</div>
</div>
<div class="control-group">
{{ form_label(form.image, 'Image', { 'attr': {'class': 'control-label'} }) }}
<div class="controls error">
{{ form_widget(form.image, { 'attr': {'class': ''} }) }}
<span class="help-inline">{{ form_errors(form.image) }}</span>
</div>
</div>
{{ form_rest(form) }}
<div class="form-actions">
<button type="submit" class="btn btn-primary">Enregistrer</button>
<a href="{{ path('parkingzone') }}" class="btn">Annuler</a>
</div>
</form>
你知道在Symfony的单元测试和功能测试之间的区别,并且你已经有一个PHPUnit的测试成功提交表单的你的控制器的测试类扩展了Symfony WebTestCase? – redbirdo 2012-07-17 09:35:50
我刚刚在底部回答了这个问题。请检查我的答案。 – 2012-07-17 13:18:03
感谢您的额外信息。有两点 - 当控制器抛出异常时,用户在生产中看到的是“Oops,发生了错误”,这可以吗?其次,正如我在原始答案中试图解释的那样,您可以通过检查来自操作的响应中包含“无法找到ParkingZone实体”来进行测试,Symfony将显示包含异常消息的页面。我会用一个例子更新我的原始答案。 – redbirdo 2012-07-18 09:08:06