mercredi 18 novembre 2015

Symfony Forms EntityType Unit Testing

I am trying to add unit test for my forms. The problem is that almost all my forms has other types like collection, entity types etc.

I do that to mock Entity Type:

/**
 * @return \PHPUnit_Framework_MockObject_MockObject
 */
protected function mockEntityType()
{
    $mockEntityManager = $this->getMockBuilder('Doctrine\ORM\EntityManager')
        ->disableOriginalConstructor()
        ->getMock();

    $mockRegistry = $this->getMockBuilder('Doctrine\Bundle\DoctrineBundle\Registry')
        ->disableOriginalConstructor()
        ->setMethods(array('getManagerForClass'))
        ->getMock();

    $mockRegistry->expects($this->any())->method('getManagerForClass')
        ->will($this->returnValue($mockEntityManager));

    $mockEntityType = $this->getMockBuilder('Symfony\Bridge\Doctrine\Form\Type\EntityType')
        ->setMethods(array('getName'))
        ->setConstructorArgs(array($mockRegistry))
        ->getMock();

    $mockEntityType->expects($this->any())->method('getName')
        ->will($this->returnValue('entity'));

    return $mockEntityType;
}

Then to use this in a test i do that for example:

public function testCompanyType()
{
     $formData = array(
        'name' => 'Test name',
        'description' => 'Test description',
    );

    $company = new Company();

    $this->fromArray($company, $formData);

    $type = new CompanyType();
    $form = $this->factory->create($type);


    // submit the data to the form directly
    $form->submit($formData);

    $this->assertTrue($form->isSynchronized());
    $this->assertEquals($company->getName(), $form->getData()->getName());

    $view = $form->createView();
    $children = $view->children;

    foreach (array_keys($formData) as $key) {
        $this->assertArrayHasKey($key, $children);
    }
}

The problem is that in line $form = $this->factory->create($type); I get error:

The option "route_name" does not exist. Defined options are: "action", "attr", "auto_initialize", "block_name", "by_reference", "choice_attr", "choice_label", "choice_list", "choice_loader", "choice_name", "choice_translation_domain", "choice_value", "choices", "choices_as_values", "class", "compound", "data", "data_class", "disabled", "em", "empty_data", "empty_value", "error_bubbling", "expanded", "group_by", "id_reader", "inherit_data", "label", "label_attr", "label_format", "loader", "mapped", "max_length", "method", "multiple", "pattern", "placeholder", "post_max_size_message", "preferred_choices", "property", "property_path", "query_builder", "read_only", "required", "translation_domain", "trim", "virtual".

It mocks somehow entity type but with wrong options. Entity Type should have route_name.

Anyone can help me fix this?

Thanks a lot.

Aucun commentaire:

Enregistrer un commentaire