如何使用EntityType字段对Symfony 4 Form进行单元测试

时间:2018-04-17 09:33:08

标签: forms unit-testing symfony symfony4

如何使用EntityType字段

对Symfony 4表单进行单元测试

当我进行测试时:

  

$ ./vendor/bin/simple-phpunit tests / Unit / Form / ProductFormTest.php

这是我终端的输出:

  

Sebastian Bergmann的PHPUnit 6.5.8

     

和贡献者。

     

运行时:PHP 7.2.4-1 + ubuntu16.04.1 + deb.sury.org + 1与Xdebug   2.7.0alpha2-dev配置:/var/www/project/phpunit.xml.dist

     

测试App \ Tests \ Unit \ Form \ ProductFormTest E
  1/1(100%)

     

时间:551毫秒,内存:6.00MB

     

有1个错误:

     

1)App \ Tests \ Unit \ Form \ ProductFormTest :: formSubmitsValidData   Symfony \ Component \ Form \ Exception \ RuntimeException:Class   “App \ Entity \ Supplier”似乎不是托管的Doctrine实体。难道   你忘了映射它吗?

     

/var/www/project/vendor/symfony/doctrine-bridge/Form/Type/DoctrineType.php:205   /var/www/project/vendor/symfony/options-resolver/OptionsResolver.php:858   /var/www/project/vendor/symfony/doctrine-bridge/Form/Type/DoctrineType.php:130   /var/www/project/vendor/symfony/options-resolver/OptionsResolver.php:766   /var/www/project/vendor/symfony/options-resolver/OptionsResolver.php:698   /var/www/project/vendor/symfony/form/ResolvedFormType.php:95   /var/www/project/vendor/symfony/form/FormFactory.php:76   /var/www/project/vendor/symfony/form/FormBuilder.php:97   /var/www/project/vendor/symfony/form/FormBuilder.php:256   /var/www/project/vendor/symfony/form/FormBuilder.php:206   /var/www/project/vendor/symfony/form/FormFactory.php:30   /var/www/project/tests/Unit/Form/ProductFormTest.php:86

     

错误!测试:1,断言:0,错误:1。

模拟ManagerRegistry类后,此错误开始。似乎在这个单元测试中没有对存在的学说实体的映射。

是否有一种干净的方法来测试带有“Symfony \ Bridge \ Doctrine \ Form \ Type \ EntityType”字段的表单?

src \ App \ Entity \ Product.php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use App\Entity\Supplier;

/**
 * Product Entity
 * 
 * @ORM\Entity(repositoryClass = "App\Repository\ProductRepository")
 * @ORM\Table(name = "product")
 */
class Product
{
    /**
     * Constructor
     */
    public function __construct()
    {
        parent::__construct();

        $this->setType(AbstractProduct::TYPE_PARENT);
    }

    /**
     * To String
     * 
     * @return string
     */
    public function __toString()
    {
        return "[" . $this->id . "] Product: " . $this->ean . " | " . $this->name;
    }

    /**
     * ID
     *
     * @var integer
     *
     * @ORM\Id
     * @ORM\Column(name = "product_id", type = "integer")
     * @ORM\GeneratedValue(strategy = "AUTO")
     */
    protected $id;

    /**
     * EAN (European Article Number)
     *
     * @var string
     *
     * @ORM\Column(name = "product_ean", type = "string", length = 13)
     */
    protected $ean;

    /**
     * Name
     *
     * @var string
     *
     * @ORM\Column(name = "product_name", type = "string", length = 128)
     */
    protected $name;

    /**
     * Description
     *
     * @var string
     *
     * @ORM\Column(name = "product_description", type = "text", nullable = true)
     */
    protected $description;

    /**
     * Supplier
     *
     * Many Products have one Supplier
     *
     * @var Supplier
     *
     * @ORM\ManyToOne(targetEntity = "Supplier", inversedBy = "products")
     * @ORM\JoinColumn(name = "supplier_id", referencedColumnName = "supplier_id")
     */
    protected $supplier;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set ean
     *
     * @param string $ean
     *
     * @return AbstractProduct
     */
    public function setEan($ean)
    {
        $this->ean = $ean;

        return $this;
    }

    /**
     * Get ean
     *
     * @return string
     */
    public function getEan()
    {
        return $this->ean;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return AbstractProduct
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set description
     *
     * @param string $description
     *
     * @return AbstractProduct
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set supplier
     *
     * @param \App\Entity\Supplier $supplier
     *
     * @return Product
     */
    public function setSupplier(Supplier $supplier = null)
    {
        $this->supplier = $supplier;

        return $this;
    }

    /**
     * Get supplier
     *
     * @return \App\Entity\Supplier
     */
    public function getSupplier()
    {
        return $this->supplier;
    }
}

SRC \应用\表格\ ProductForm.php

namespace App\Form;

use App\Entity\Supplier;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;

class ProductForm extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $translationDomain = "product";

        /*
         * Card
         */
        $builder->add("ean", TextType::class, [
            "label"              => "product.ean",
            "required"           => true,
            "translation_domain" => $translationDomain,
        ]);

        $builder->add("name", TextType::class, [
            "label"              => "product.name",
            "required"           => true,
            "translation_domain" => $translationDomain,
        ]);

        $builder->add("supplier", EntityType::class, [
            "class"              => Supplier::class,
            "choice_label"       => "name",
            "label"              => "supplier.name",
            "required"           => false,
            "translation_domain" => "supplier",
        ]);
    }
}

测试\单位\表格\ ProductFormTest.php

namespace App\Tests\Unit\Form;

use App\Entity\Product;
use App\Form\ProductForm;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Bridge\Doctrine\ManagerRegistry;
use Symfony\Component\Form\PreloadedExtension;
use Symfony\Component\Form\Test\TypeTestCase;

class ProductFormTest extends TypeTestCase
{
    /**
     * @var ManagerRegistry
     */
    private $_managerRegistry;

    /**
     * {@inheritdoc}
     */
    protected function setUp()
    {
        $this->_managerRegistry = $this->createMock(ManagerRegistry::class);

        parent::setUp();
    }

    /**
     * {@inheritdoc}
     */
    protected function tearDown()
    {
        $this->_managerRegistry = null;

        parent::tearDown();
    }

    /**
     * {@inheritdoc}
     */
    protected function getExtensions()
    {
        $entityType = new EntityType($this->_managerRegistry);

        return [
            new PreloadedExtension([$entityType], [])
        ];
    }

    /**
     * @test
     */
    public function formSubmitsValidData()
    {
        $createdAt = new \DateTime();

        $formData = [
            "ean"         => "8718923400440",
            "name"        => "Plumbus",
            "description" => "This is a household device so common it does not need an introduction",
        ];

        $productComparedToForm = new Product();
        $productComparedToForm
            ->setEan($formData["ean"])
            ->setName($formData["name"])
        ;

        $productHandledByForm = new Product();

        $form = $this->factory->create(ProductForm::class, $productHandledByForm);

        $form->submit($formData);

        static::assertTrue($form->isSynchronized());
        static::assertEquals($productComparedToForm, $productHandledByForm);

        $view = $form->createView();

        foreach (array_keys($formData) as $key) {
            static::assertArrayHasKey($key, $view->children);
        }
    }
}

1 个答案:

答案 0 :(得分:-1)

首先,您的测试用例应该从Symfony\Component\Form\Test\TypeTestCase延伸。

然后你的测试应该是这样的:

// Example heavily inspired by EntityTypeTest inside the Symfony Bridge
class ProductTypeTest extends TypeTestCase
{
    /**
     * @var EntityManager
     */
    private $em;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject|ManagerRegistry
     */
    private $emRegistry;

    protected function setUp()
    {
        $this->em = DoctrineTestHelper::createTestEntityManager();
        $this->emRegistry = $this->createRegistryMock('default', $this->em);

        parent::setUp();

        $schemaTool = new SchemaTool($this->em);

        // This is the important part for you !
        $classes = [$this->em->getClassMetadata(Supplier::class)];

        try {
            $schemaTool->dropSchema($classes);
        } catch (\Exception $e) {
        }

        try {
            $schemaTool->createSchema($classes);
        } catch (\Exception $e) {
        }
    }
    protected function createRegistryMock($name, $em)
    {
        $registry = $this->getMockBuilder('Doctrine\Common\Persistence\ManagerRegistry')->getMock();
        $registry->expects($this->any())
            ->method('getManager')
            ->with($this->equalTo($name))
            ->will($this->returnValue($em));

        return $registry;
    }

    protected function getExtensions()
    {
        return array_merge(parent::getExtensions(), array(
            new DoctrineOrmExtension($this->emRegistry),
        ));
    }

    protected function tearDown()
    {
        parent::tearDown();

        $this->em = null;
        $this->emRegistry = null;
    }
}