Symfony2 Custom form type using entity trying to test it

半城伤御伤魂 提交于 2019-12-01 03:20:41

问题


I am trying to test a form type I have creating that uses a field with class entity

here is the creation of the form

$builder
            ->add('name', 'text')
            ->add('description', 'textarea')
            ->add('services', 'entity', array('class' => 'MyBundle:Service', 'group_by' => 'category.name', 'property' => 'name', 'multiple' => true, 'required' => false));

This works very nice when I build the form, but then I am trying to unit test this type

Following this example on how to test my custom form types

I am getting this error

Symfony\Component\Form\Exception\Exception: Could not load type "entity"

The error is caused at the beginning of unit test at this command:

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

any ideas on how to fix this error in order to test my custom form type using entities?

thanks in advance


回答1:


I guess you can't unit test form with entity types, because it's defined as a service. Have you tried adding it manually?

EDIT: IMHO you should mock the entity type, because it involves doctrine, which depends on an existing database connection and so on the full kernel loaded. So you're not unit testing any more. This would be a functional test. Maybe this the reason, why it's not available in the unit test.




回答2:


According to the symfony docs under Adding a Type your Form Depends on

To create your form correctly, you need to make the type available to the form factory in your test. The easiest way is to register it manually before creating the parent form using the PreloadedExtension class:

class TestedTypeTest extends TypeTestCase
{
    protected function getExtensions()
    {
        $childType = new TestChildType();
        return array(new PreloadedExtension(array(
            $childType->getName() => $childType,
        ), array()));
    }

    public function testSubmitValidData()
    {
        $type = new TestedType();
        $form = $this->factory->create($type);

        // ... your test
    }
}



回答3:


Add null for second parameters in method create.

$type = new MyType();
$form = $this->factory->create($type, null);


来源:https://stackoverflow.com/questions/16341149/symfony2-custom-form-type-using-entity-trying-to-test-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!