2017-10-06 64 views
1

如何对绑定到实体的表单进行功能测试(而非单元测试)?Symfony/phpUnit:修改实体的表单的功能测试

语境

假设你有一个实体“驾驶”,有场“id”和另一场“号牌”,和页面编辑关于汽车的数据。

CarController.php

//... 

public function imsiDetailsChangeAction(Request $request) 
{ 
    $car_id = $request->get('car_id'); 
    $car = $this->getDoctrine()->getRepository('ClnGsmBundle:Car')->Find($car_id); 

    if ($simCard != null) 
    { 
    $form = $this->createForm(new CarType()), $car); 

    if($request->isMethod('POST')) 
    { 
     $form->bind($request); 

     if ($form->isValid()) 
     { 
     $em = $this->getDoctrine()->getManager(); 
     $em->flush(); 

     return $this->redirect($this->generateUrl('car_view', array('car_id' => $car->getId()))); 
     } 
    } 
    } 
    else 
    { 
    throw new NotFoundHttpException(); 
    } 

    return $this->render('SiteBundle:Car:carEdit.html.twig', array('car' => $car, 'form' => $form->createView())); 
} 

//... 

我使用PHPUnit的做想

测试什么如下:

  • 创建一个汽车实体与号牌“QWE-456 “

  • lo广告用的履带形式

  • 的页面,以形式为“阿塞拜疆-123”更换号牌,并提交表单

  • 断言,我的车实体号牌现在等于“阿塞拜疆-123”

我试过

(以防万一:我自己的代码是有点不同的,这里是我会与汽车例子做)

CarControllerTest.php

//... 

public function SetUp() 
{ 
    //start kernel, stores entity manager in $this->em and client in $this->client 
} 

//... 

public function testEditForm() 
{ 
    $car = new Car(); 
    $car->setNumberPlate("QWE-456"); 

    $this->entityManager->persist($simCard); 
    $this->em->flush(); 

    $crawler = $this->client->request('GET', '/fr/Car/edit/'.$car->getId()); 
    $this->assertEquals(200, $this->client->getResponse()->getStatusCode()); 

    $formNode = $crawler->filterXpath("//div[@id='main']//form"); 
    $form = $formNode->form(array(
    'car[plateNumber]'=>'AZE-123', 
)); 

    //var_dump($car->getPlateNumber()); 
    $this->client->submit($form); 
    //var_dump($car->getPlateNumber()); 
    $this->assertEquals('AZE-123',$car->getPlateNumber); 
} 

我期望此测试通过,和第二的var_dump打印 “AZE-123” 而不是 “QWE-456”。但我的实体没有修改。

我该怎么做?

回答

1

您应该刷新的数据从数据库中重装吧:refresh method为你做,那么试试这个:

$this->client->submit($form); 

    $this->em->refresh($car); 

    $this->assertEquals('AZE-123',$car->getPlateNumber); 

我建议你为了验证正确的交互HTTP应答前检查,作为例子:

$response = $this->client->getResponse(); 
    $this->assertTrue($response->isRedirection()); 

希望这有助于

+0

非常感谢您的回答,并抱歉,没有测试它越快!我不知道这种方法,但我应该虽然在数据库中的元组被修改了,但没有更新我的实体...但是,这个解决方案仍然不起作用,因为“SQLSTATE [HY000]:一般错误:1没有这样表:汽车“。我认为这是因为内核再次启动并且数据库受到了损伤(在一次测试中尝试执行多个请求时,我遇到了类似的错误)。你不应该这样做吗?我应该重写默认客户端来改变这种行为,就像我在这里看到的几个答案一样? – Seipas

+0

(我指的是:http://alexandre-salome.fr/blog/Symfony2-Isolation-Of-Tests在这里找到:https://stackoverflow.com/questions/12823021/issue-with-the-entity -manager-and-phpunit-in-symfony-2?rq = 1(刚才我看到我的问题是这个问题的重复...)) – Seipas

+0

您是否成功创建了测试数据库?如果您登录到测试数据库,您是否看到相关表格? – Matteo