Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Symfony2 Forms causes Could not load type "entity"

I am testing a Form Type I defined for an application. During testing the form type, using symfony's TypeTestCase class a message "Could not load type "entity"" appears. What can I do to solve the problem??

class MyType extends AbstractType {
  public function buildForm(FormBuilderInterface $builder, array $options) {
    $builder->add('otherType', 'entity', array('class' => 'Bundle:OtherType'));
  }
}

class MyTypeTest extends TypeTestCase {
  public function testSth() {
    $type = new MyType();
  }
}
like image 448
Benny Avatar asked May 03 '13 09:05

Benny


1 Answers

I already got the same problem when testing some of my customized Types.

Here's the way I figure it out (by mocking EntityType),

First, make sure your test class extends TypeTestCase,

class MyTypeTest extends TypeTestCase
{
    // ... 
}

Then, add a preloaded extension to your form factory in order to take into account the EntityType

protected function setUp()
{
    parent::setUp();

    $this->factory = Forms::createFormFactoryBuilder()
      ->addExtensions($this->getExtensions())
      ->getFormFactory();
}
// Where this->getExtensions() returns the EntityType preloaded extension 
// (see the last step)    
}

And finally, add an Entity Type mock to your preloaded extension.

protected function getExtensions()
{
    $mockEntityType = $this->getMockBuilder('Symfony\Bridge\Doctrine\Form\Type\EntityType')
        ->disableOriginalConstructor()
        ->getMock();

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

    return array(new PreloadedExtension(array(
            $mockEntityType->getName() => $mockEntityType,
    ), array()));
}

But, you may need to ...

Mock the registry that DoctrineType takes as parameter when calling its default constructor because it's used by setDefaultOptions() (Keep in mind that EntityType extends DoctrineType) to take into account class and property options of your Entity field.

Your may then need to mock the entityType as follow:

$mockEntityManager = $this->getMockBuilder('\Doctrine\ORM\EntityManager')->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'));
like image 140
Ahmed Siouani Avatar answered Oct 14 '22 13:10

Ahmed Siouani