Модульное тестирование форм Symfony4 с коллекциями

Приступая к работе с формами модульного тестирования, я пытаюсь протестировать форму, содержащую коллекцию типов форм. Мой тест не подтверждает, что объект FeatureOption обрабатывается после отправки моей формы.

Как полностью протестировать эту форму со всеми предоставленными мной данными?

$ ./vendor/bin/simple-phpunit tests / Unit / Form / PHPUnit 6.5.7

Время выполнения: PHP 7.2.4-1 + ubuntu16.04.1 + deb.sury.org + 1 с Xdebug 2.7.0alpha2-dev Конфигурация: /var/www/phpunit.xml.dist

Тестовые тесты / Блок / Форма / F
1/1 (100%)

Время: 599 мс, Память: 6,00 МБ

Произошел 1 сбой:

1) App \ Tests \ Unit \ Form \ FeatureFormTest :: submitValidData Ошибка при утверждении, что два объекта равны.
--- Ожидаемый
+++ Actual @@ @@ - 0 => App \ Entity \ FeatureOption Object (...)

/var/www/tests/Unit/Form/FeatureFormTest.php:55

ОТКАЗЫ! Тесты: 1, Утверждения: 2, Неудачи: 1.

src \ Entity \ Feature.php:

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;

/**
 * Feature Entity
 * 
 * @ORM\Entity()
 * @ORM\Table(name = "feature")
 */
class Feature extends AbstractEntity
{
    /**
     * Constructor
     */
    public function __construct()
    {
        parent::__construct();

        $this->options = new ArrayCollection();
    }
    /**
     * ID
     * 
     * @var integer
     * 
     * @ORM\Id
     * @ORM\Column(name = "feature_id", type = "integer")
     * @ORM\GeneratedValue(strategy = "AUTO")
     */
    protected $id;

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

    /**
     * Options
     *
     * @var ArrayCollection
     * 
     * @ORM\OneToMany(targetEntity = "FeatureOption", mappedBy = "feature", cascade = { "persist", "remove" }, fetch = "EAGER")
     */
    protected $options;

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

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

        return $this;
    }

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

    /**
     * Add option
     *
     * @param \App\Entity\FeatureOption $option
     *
     * @return Feature
     */
    public function addOption(FeatureOption $option)
    {
        $option->setFeature($this);

        $this->options[] = $option;

        return $this;
    }

    /**
     * Remove option
     *
     * @param \App\Entity\FeatureOption $option
     */
    public function removeOption(FeatureOption $option)
    {
        $this->options->removeElement($option);
    }

    /**
     * Get options
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getOptions()
    {
        return $this->options;
    }
}

SRC \ Entity \ FeatureOption.php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;

/**
 * Feature Entity
 * 
 * @ORM\Entity()
 * @ORM\Table(name = "feature_option")
 */
class FeatureOption extends AbstractEntity
{
    /**
     * Constructor
     */
    public function __construct()
    {
        parent::__construct();
    }

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

    /**
     * Value
     *
     * @var string
     * 
     * @ORM\Column(name = "feature_option_value", type = "string", length = 256)
     */
    protected $value;

    /**
     * Feature
     *
     * @var Feature
     * 
     * @ORM\ManyToOne(targetEntity = "Feature", inversedBy = "options")
     * @ORM\JoinColumn(name = "feature_id", referencedColumnName = "feature_id")
     */
    protected $feature;

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

    /**
     * Set value
     *
     * @param string $value
     *
     * @return FeatureOption
     */
    public function setValue($value)
    {
        $this->value = $value;

        return $this;
    }

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

    /**
     * Set feature
     *
     * @param \App\Entity\Feature $feature
     *
     * @return FeatureOption
     */
    public function setFeature(Feature $feature = null)
    {
        $this->feature = $feature;

        return $this;
    }

    /**
     * Get feature
     *
     * @return \App\Entity\Feature
     */
    public function getFeature()
    {
        return $this->feature;
    }
}

SRC \ Форма \ FeatureForm.php

namespace App\Form;

use App\Form\Type\FeatureOptionType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;

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

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

        $builder->add("options", CollectionType::class, [
            "label"              => "feature.options",
            "entry_type"         => FeatureOptionType::class,
            "by_reference"       => false,
            "allow_add"          => true,
            "allow_delete"       => true,
            'prototype'          => true,
            "translation_domain" => $translationDomain,
        ]);
    }
}

SRC \ Форма \ Тип \ FeatureOptionType.php

namespace App\Form\Type;

use App\Entity\FeatureOption;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

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

        $builder->add("value", TextType::class, [
            "label"              => "feature.option.value",
            "required"           => true,
            "translation_domain" => $translationDomain,
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => FeatureOption::class,
        ));
    }
}

тесты \ Unit \ Form \ FeatureFormTest.php

namespace App\Tests\Unit\Form;

use App\Entity\Feature;
use App\Entity\FeatureOption;
use App\Form\FeatureForm;
use App\Form\Type\FeatureOptionType;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Form\PreloadedExtension;
use Symfony\Component\Form\Test\TypeTestCase;

class FeatureFormTest extends TypeTestCase
{
    /**
     * @test
     */
    public function submitValidData()
    {
        $date = new \DateTime();

        $featureOption = new FeatureOption();
        $featureOption->setValue("Indestructable");

        $formData = [
            "name"      => "Durability",
            "options"   => new ArrayCollection(array($featureOption)),
        ];

        $featureComparedToForm = new Feature();
        $featureComparedToForm->setCreatedAt($date);
        $featureComparedToForm->setName($formData["name"]);

        foreach ($formData["options"] as $option) {
            $featureComparedToForm->addOption($option);
        }

        $featureHandledByForm = new Feature();
        $featureHandledByForm->setCreatedAt($date);

        $form = $this->factory->create(FeatureForm::class, $featureHandledByForm);

        $form->submit($formData);

        static::assertTrue($form->isSynchronized());
        static::assertEquals($featureComparedToForm, $featureHandledByForm);

        $view = $form->createView();

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

    /**
     * {@inheritdoc}
     */
    public function getExtensions()
    {
        $featureOptionType = new FeatureOptionType();

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

person murtho    schedule 11.04.2018    source источник


Ответы (1)


потому что $ featureComparedToForm и $ featureHandledByForm - это два разных объекта. если вы хотите сравнить атрибуты, просто сравните атрибуты, а не все объекты.

person yawa yawa    schedule 12.04.2018