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();
}
}
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'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With