问题描述
我正在测试我为应用程序定义的表单类型.在测试表单类型期间,使用 symfony 的 TypeTestCase 类会出现一条消息无法加载类型实体"".我能做些什么来解决这个问题??
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.
这是我解决的方法(通过模拟 EntityType),
Here's the way I figure it out (by mocking EntityType),
首先,确保您的测试类扩展了 TypeTestCase,
class MyTypeTest extends TypeTestCase
{
// ...
}
然后,将 预加载扩展 添加到您的 form factory 为了考虑到 EntityType
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('SymfonyBridgeDoctrineFormTypeEntityType')
->disableOriginalConstructor()
->getMock();
$mockEntityType->expects($this->any())->method('getName')
->will($this->returnValue('entity'));
return array(new PreloadedExtension(array(
$mockEntityType->getName() => $mockEntityType,
), array()));
}
但是,您可能需要...
模拟 注册表 DoctrineType 在调用其默认构造函数时作为参数因为它被 setDefaultOptions()
使用(请记住 EntityType 扩展 DoctrineType) 考虑到 类 和 属性 您的 实体字段.
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.
然后您可能需要按如下方式模拟 entityType:
Your may then need to mock the entityType as follow:
$mockEntityManager = $this->getMockBuilder('DoctrineORMEntityManager')->getMock();
$mockRegistry = $this->getMockBuilder('DoctrineBundleDoctrineBundleRegistry')
->disableOriginalConstructor()
->setMethods(array('getManagerForClass'))
->getMock();
$mockRegistry->expects($this->any())->method('getManagerForClass')
->will($this->returnValue($mockEntityManager));
$mockEntityType = $this->getMockBuilder('SymfonyBridgeDoctrineFormTypeEntityType')
->setMethods(array('getName'))
->setConstructorArgs(array($mockRegistry))
->getMock();
$mockEntityType->expects($this->any())->method('getName')
->will($this->returnValue('entity'));
这篇关于测试 Symfony2 Forms 导致无法加载类型“实体"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!