Symfony2 Custom form type using entity trying to test it
Asked Answered
M

3

6

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

Mettah answered 2/5, 2013 at 14:50 Comment(1)
Currently, Symfony supports the EntityType out of the box, but doesn't have a proper way to unit test it: github.com/symfony/symfony/issues/15098.Shipload
S
3

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.

Spinster answered 2/5, 2013 at 21:19 Comment(1)
From my understanding, this method is used when a form type depends on another form type, where in my cause its an entity that is being passed to a choice entity. I have managed to test simple form types but not the ones using entity type :(Mettah
G
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
    }
}
Gonna answered 23/6, 2015 at 19:2 Comment(0)
A
0

Add null for second parameters in method create.

$type = new MyType();
$form = $this->factory->create($type, null);
Anxious answered 16/6, 2015 at 14:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.