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

时间:2013-05-03 09:27:00

标签: forms testing symfony phpunit

我正在测试为应用程序定义的表单类型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();
  }
}

2 个答案:

答案 0 :(得分:14)

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

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

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

class MyTypeTest extends TypeTestCase
{
    // ... 
}

然后,在preloaded extension添加form factory,以便考虑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)    
}

最后,向Entity Type添加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()));
}

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

在调用默认构造函数时,将registry作为参数的DoctrineType进行模拟,因为它setDefaultOptions()使用了(请记住EntityType扩展DoctrineType)要考虑classpropertyEntity field选项。

您可能需要模拟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'));

答案 1 :(得分:0)

Ahmed Siouani的答案写得很好,让我了解如何在Extension中添加TypeTestCase

但是如果你想进行综合测试,在这种情况下谁比单元测试简单得多,你可以这样做:

protected function getExtensions()
{
    $childType = new TestChildType();
    return array(new PreloadedExtension(array(
        $childType->getName() => $childType,
    ), array()));
}

如本文档中所述:http://symfony.com/doc/current/cookbook/form/unit_testing.html#adding-a-type-your-form-depends-on