在测试我的一些自定义类型时,我已经遇到了同样的问题。
这是我弄清楚的方法(通过模拟EntityType),
首先,确保您的测试类扩展TypeTestCase,
class MyTypeTest extends TypeTestCase
{
// ...
}
然后,将预加载的扩展添加到您的表单工厂,以考虑到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)
}
最后,在预加载的扩展中添加一个实体类型模拟。
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()));
}
但是,您可能需要...
模拟DoctrineType在调用其默认构造函数时作为参数的注册表,因为(请记住EntityType扩展DoctrineType)使用它来考虑Entity 字段的类和属性选项。setDefaultOptions()
然后,您可能需要模拟 entityType 如下:
$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'));