如何在symfony功能测试中测试事件和事件监听器?

时间:2014-08-06 22:41:04

标签: php symfony phpunit symfony-forms functional-testing

我有2个依赖字段,这些字段是用PRE_SET_DATA表单事件创建/填充的,但是当我为editAction运行我的功能测试时,我得到一个表单错误"这个字段是必需的",即使我" 39; m将这些字段的值发送给请求。关于如何解决这个问题的任何想法?

class AspectoControllerTest extends WebTestCase {

public function testCompleteScenario()
{
    ...

    // register a new Aspecto to the database, because we don't have a route
    $em = $client->getContainer()->get('doctrine.orm.entity_manager');

    $lineamiento = new Lineamiento();
    $lineamiento
        ->setNombre('Testing Lineamiento'.rand(0,99))
        ->setFechaExpedicion(new \DateTime())
        ->setFechaExpiracion(new \DateTime())
    ;

    $factor = new Factor();
    $factor
        ->setNombre('Testing Factor'.rand(0,99))
        ->setDescripcion('Testing Factor')
        ->setNivel('institucional')
        ->setLineamiento($lineamiento)
    ;

    $caracteristica = new Caracteristica();
    $caracteristica
        ->setNombre('Testing Carac'.rand(0,99))
        ->setDescripcion('Testing Carac')
        ->setFactor($factor)
    ;

    $lineamiento->addFactor($factor);
    $factor->addCaracteristica($caracteristica);

    $em->persist($lineamiento);
    $em->flush();

    // Get the list of Aspecto
    $crawler = $client->request('GET', '/secure/aspecto/new/caracteristica/'.$caracteristica->getId());
    $this->assertEquals(200, $client->getResponse()->getStatusCode(), "Unexpected HTTP status code for GET /secure/aspecto/new/caracteristica/".$caracteristica->getId());

    // Fill in the form and submit it, THIS WORKS
    $form = $crawler->selectButton('Guardar')->form();

    $array = array(
        'udes_aquizbundle_aspectonew' => array(
            'codigo' => 'a'.rand(1, 99),
            'nombre'  => 'Testing Aspecto '.rand(1, 99),
            'lineamiento' => $lineamiento->getId(),
            'factor' => $factor->getId(),
            'caracteristicas' => $caracteristica->getId(),
            'tipo' => rand(1, 3),
            'facilitadorResultado' => 'Facilitador',
            '_token' => $form->get('udes_aquizbundle_aspectonew[_token]')->getValue()
        )
    );

    $client->request('POST', $form->getUri(), $array);
    $crawler = $client->followRedirect();

    // Check data in the show view
    $this->assertGreaterThan(0, $crawler->filter('h4.widgettitle:contains("Testing Aspecto")')->count(), 'Missing element h4:contains("Testing Aspecto")');

    // Edit action, THIS DOES NOT WORK
    $crawler = $client->click($crawler->selectLink('Editar')->link());

    // Fill in the form and submit it
    $form = $crawler->selectButton('Guardar')->form();
    $array = array(
        'udes_aquizbundle_aspectoedit' => array(
            'codigo' => 'a'.rand(1, 99),
            'nombre'  => 'Edit Testing Aspecto '.rand(1, 99),
            'lineamiento' => $lineamiento->getId(),
            'factor' => $factor->getId(),
            'caracteristicas' => $caracteristica->getId(),
            'tipo' => rand(1, 3),
            'facilitadorResultado' => 'Resultado',
            '_token' => $form->get('udes_aquizbundle_aspectoedit[_token]')->getValue()
        )
    );

    $client->request('PUT', $form->getUri(), $array);

    $crawler = $client->followRedirect();

    // Delete the entity
    $client->submit($crawler->selectButton('Eliminar')->form());
    $crawler = $client->followRedirect();

    // Check the entity has been delete on the list
    $this->assertNotRegExp('/Edit Testing Aspecto/',    $client->getResponse()->getContent());

    #Removed Entity Used
    $em->remove($caracteristica);
    $em->remove($factor);
    $em->remove($lineamiento);

    $em->flush();
}

}

这是表格:

class AspectoEditType extends AspectoType {
/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    parent::buildForm($builder, $options);
    $caracteristica = $options['caracteristica'];
    $builder
        ->remove('createdAt')
        ->remove('updatedAt')
        ->remove('instrumentoReactivos')
        ->add('documentos' , 'entity' , array('class' => 'UdesAquizBundle:Documento',
                                              'expanded' => true,
                                              'multiple' => true,
                                              'property' => 'nombre',
                                              'attr' => array('class' => 'form-control input-block-level')
                                             ))
        ->add('caracteristicas', 'shtumi_dependent_filtered_entity', array(
            'entity_alias' => 'factor_caracteristica',
            'empty_value' => 'Seleccione la Caracteristica',
            'parent_field' => 'factor',
            'mapped' => false,
            'attr' => array(
                'class' => 'form-control dependent-caracteristica input-block-level'
            ),
            'data' => $caracteristica,
            'data_class' => null
        ))
    ;

    $builder->addEventListener(FormEvents::PRE_SET_DATA,function (FormEvent $event) use ($caracteristica) {
        $form = $event->getForm();
        $factor = $caracteristica->getFactor();
        $lineamiento = $factor->getLineamiento();
        $form
            ->add('lineamiento', 'entity', array(
                'label' => 'Lineamiento',
                'class' => 'Udes\AquizBundle\Entity\Lineamiento',
                'property' => 'nombre',
                'mapped' => false,
                'data' => $lineamiento,
                'empty_value' => 'Seleccione un lineamiento',
                'attr' => array(
                    'class' => 'form-control load-factores input-block-level',
                ),
            ))
            ->add('factor', 'shtumi_dependent_filtered_entity', array(
                'entity_alias' => 'lineamiento_factor',
                'empty_value' => 'Seleccione el Factor',
                'parent_field' => 'lineamiento',
                'data_class' => null,
                'data' => $factor,
                'mapped' => false,
                'attr' => array(
                    'class' => 'form-control dependent-factor load-caracteristicas input-block-level'
                ),
            ))
        ;
    });
}

...
}

1 个答案:

答案 0 :(得分:1)

如果表单中的实体有断言(例如@Valid),则表单验证所有实体都有效。检查是否有任何实体或任何@Valid注释缺少字段。