php - 如何在 symfony2 功能测试中测试表单事件和事件监听器?

标签 php symfony phpunit symfony-forms functional-testing

我有 2 个依赖字段,它们是用 PRE_SET_DATA 表单事件创建/填充的,但是当我运行 editAction 的功能测试时,我收到表单错误“此字段是必需的”,即使我正在发送值请求的那些字段。关于如何解决这个问题的任何想法?

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'
                ),
            ))
        ;
    });
}

...
}

最佳答案

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

关于php - 如何在 symfony2 功能测试中测试表单事件和事件监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25171453/

相关文章:

php - 如何在单个数组中获取 php PDO QUERY 结果集而不是嵌套在一个数组中

symfony - Amazon ElasticBeanstalk 中的单实例 cronjob

function - 如何在 Symfony 中使用函数?

php - 使用 Mockery 模拟在另一个静态方法中调用的静态方法

php - MySQL 查询未按预期返回

php - 尝试使用 codeigniter 将其写入数据库时​​,整数更改为随机字符串

PHP,如何查找字符串中是否有某个单词?

php - Symfony Doctrine 冲洗实体

php - 使用 Doctrine 在 Symfony2 中测试 Controller

laravel-5 - PhpUnit 测试,如果表单中有多个同名复选框,如何检查复选框