How to check symfony form type using constructor

I'm currently struggling with TypeTestCase from Symfony by testing the type of the form with a constructor. While the official solution that registers the form as a service works well in the application, the same type of form cannot be tested with TypeTestCase. Since TypeTestCase extends from FormIntegrationTestCase and exits \ PHPUnit_Framework_TestCase instead of KernelTestCase. FormFactory in TypeTestCase does not search / does not search for forms registered as services and throws an error that causes phpunit:

Tests\DemoBundle\Form\Type\DemoTypeTest::testSubmitValidData
Missing argument 1 for DemoBundle\Form\Type\DemoType::__construct(), called in /var/www/vendor/symfony/symfony/src/Symfony/Component/Form/FormRegistry.php on line 90 and defined

The only way that I see at the moment is not serving the dependency via the constructor, using optionsResolver in configureOptions, sets the required element using the setRequired method for the dependency.

Here are the relevant parts of the code:

DemoType.php

[...]
class DemoType extends AbstractType
{
    /**
     * @var EntityManager
     */
    protected $entityManager;

    public function __construct($entityManager)
    {
        $this->entityManager = $entityManager;
    }
[...]

services.yml

app.form.type.demo:
    class: DemoBundle\Form\Type\DemoType
    arguments: ["@doctrine.orm.entity_manager"]
    tags:
        - { name: form.type }

DemoTypeTest.php

[...]
class DemoTypeTest extends TypeTestCase
{

    protected function getExtensions()
    {
        $classMetadata = $this->getMock(ClassMetadata::class, [], [], '', false);
        /* @var ValidatorInterface|\PHPUnit_Framework_MockObject_MockObject $validator */
        $validator = $this->getMock(ValidatorInterface::class);
        $validator->method('validate')->will($this->returnValue(new ConstraintViolationList()));
        $validator->method('getMetadataFor')->will($this->returnValue($classMetadata));
        return [
            new ValidatorExtension($validator),
        ];
    }

    public function testSubmitValidData()
    {
        $formData = [
            'some' => 'data',
        ];

        $form = $this->factory->create(DemoType::class);

[...]
+4
source share
1 answer

You can create an instance of FormType and submit it to the factory form, as described in the doc .

You can mock Doctrine Entity Manager, for example:

public function testSubmitValidData()
{
  // Mock the FormType: entity
  $em = $this->getMockBuilder('\Doctrine\ORM\EntityManager')
      ->disableOriginalConstructor()
      ->getMock();

    $type = new DemoType($em);
    $formData = [
        'some' => 'data',
    ];

    $form = $this->factory->create($type);
    ...

An example of bullying a stack of Doctrine objects to simulate a repo method, you can see this answer or just ask :)

Hope for this help

0
source

Source: https://habr.com/ru/post/1626260/


All Articles