How to unit test Symfony 4 Form with EntityType field

梦想与她 提交于 2020-01-24 13:24:27

问题


How to unit test Symfony 4 Form with EntityType field

When I run my test:

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

This is the output in my terminal:

PHPUnit 6.5.8 by Sebastian Bergmann

and contributors.

Runtime: PHP 7.2.4-1+ubuntu16.04.1+deb.sury.org+1 with Xdebug 2.7.0alpha2-dev Configuration: /var/www/project/phpunit.xml.dist

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

Time: 551 ms, Memory: 6.00MB

There was 1 error:

1) App\Tests\Unit\Form\ProductFormTest::formSubmitsValidData Symfony\Component\Form\Exception\RuntimeException: Class "App\Entity\Supplier" seems not to be a managed Doctrine entity. Did you forget to map it?

/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

ERRORS! Tests: 1, Assertions: 0, Errors: 1.

This error started after mocking the ManagerRegistry class. It seems that in this unit test there is no mapping for doctrine entities present.

Is there a clean way to test a form with "Symfony\Bridge\Doctrine\Form\Type\EntityType" fields?

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\App\Form\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",
        ]);
    }
}

tests\Unit\Form\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:


First your test case should extends from Symfony\Component\Form\Test\TypeTestCase.

Then your test should look like this:

// 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;
    }
}


来源:https://stackoverflow.com/questions/49874598/how-to-unit-test-symfony-4-form-with-entitytype-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!