测试Symfony2 Forms导致无法加载类型"entity"

Ben*_*nny 9 forms testing phpunit symfony

我正在测试为应用程序定义的表单类型I. 在测试表单类型期间,使用symfony的TypeTestCase类会出现消息"无法加载类型"实体"".我该怎么做才能解决问题?

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();
  }
}
Run Code Online (Sandbox Code Playgroud)

Ahm*_*ani 14

在测试我的一些自定义类型时,我已经遇到了同样的问题.

这是我弄清楚的方式(通过模拟EntityType),

首先,确保您的测试类扩展了TypeTestCase,

class MyTypeTest extends TypeTestCase
{
    // ... 
}
Run Code Online (Sandbox Code Playgroud)

然后,将预加载的扩展添加到表单工厂,以便考虑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)    
}
Run Code Online (Sandbox Code Playgroud)

最后,将Entity Type模拟添加到预加载的扩展中.

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()));
}
Run Code Online (Sandbox Code Playgroud)

但是,你可能需要......

在调用其默认构造函数时,将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'));
Run Code Online (Sandbox Code Playgroud)

  • 您好,我按照您发布的内容但是,我收到了一个错误:从/usr/share/php/PHPUnit/Framework/MockObject/Generator.php中的上下文'PHPUnit_Framework_MockObject_Generator'调用受保护的Doctrine\ORM\EntityManager :: __ construct()在第237行 (13认同)