在Symfony的How to Unit Test your Forms文档中,很简单。
但是我有一个问题。
我有一个带有某些默认值的学说实体。以及与模型绑定的表单类型。我的意思是'data_class'
是实体。在这种情况下,当我调用$form->submit();
和$form->isSynchronized()
时,默认值就消失了。并且$this->assertEquals($object, $objectToCompare);
失败。
如何测试具有某些默认值的绑定到模型类的表单类型?
我怀疑这是一个错误。在$this->factory->create(TestedType::class, $objectToCompare);
中创建表单类型实例时,应应用$objectToCompare
的默认值。
或者,我应该创建一个扩展来处理吗?
这是示例代码。为了简化代码,我将理论实体更改为简单模型。
为进行比较,我添加了2个属性:一个具有默认值,另一个没有。
// AppBundle/Model/TestObject.php
namespace AppBundle\Model;
class TestObject
{
private $test;
private $test2 = 'default value';
public function getTest()
{
return $this->test;
}
public function setTest($test)
{
$this->test = $test;
}
public function getTest2()
{
return $this->test2;
}
public function setTest2($test2)
{
$this->test2 = $test2;
}
}
很简单。
'data_class'
// AppBundle/Form/Type/TestedType.php
namespace AppBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use AppBundle\Model\TestObject;
class TestedType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('test', TextType::class);
$builder->add('test2', TextType::class);
$builder->add('save', SubmitType::class);
}
public function configureOptions(OptionsResolver $resolver)
{
parent::configureOptions($resolver);
$resolver->setDefaults(array(
'data_class' => TestObject::class,
));
}
}
它是How to Unit Test your Forms的少许修改版本。
$object
填充了属性访问权限// tests/AppBundle/Form/Type/TestedTypeTest.php
namespace Tests\AppBundle\Form\Type;
use AppBundle\Form\Type\TestedType;
use AppBundle\Model\TestObject;
use Symfony\Component\Form\Test\TypeTestCase;
use Symfony\Component\PropertyAccess\PropertyAccess;
class TestedTypeTest extends TypeTestCase
{
public function testSubmitValidData()
{
$formData = [
'test' => 'test',
];
$objectToCompare = new TestObject();
$form = $this->factory->create(TestedType::class, $objectToCompare);
$object = new TestObject();
$propertyAccessor = PropertyAccess::createPropertyAccessor();
foreach ($formData as $key => $value) {
$propertyAccessor->setValue($object, $key, $value);
}
$form->submit($formData);
$this->assertTrue($form->isSynchronized());
$this->assertEquals($object, $objectToCompare);
}
}