9

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

2 回答 2

15

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

这是我弄清楚的方法(通过模拟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'));
于 2013-10-28T14:57:28.313 回答
0

Ahmed Siouani 的回答写得很好,让我了解如何ExtensionTypeTestCase.

但是如果你想做一个比单元测试简单得多的集成测试,你可以这样做:

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

于 2015-04-03T09:21:26.977 回答