gpt4 book ai didi

php - 使用实体对 Symfony 表单进行单元测试

转载 作者:搜寻专家 更新时间:2023-10-31 21:06:50 25 4
gpt4 key购买 nike

我无法对内部具有“实体”字段的 Symfony 表单进行单元测试。

我找到了潜在的解决方案 herehere ,但是我无法让它们工作。

这是我的代码:

FormsTest.php

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

$this->factory = Forms::createFormFactoryBuilder()
->addExtensions($this->getExtensions())
->getFormFactory();
}

protected function getExtensions()
{
$mockEntityType = $this->getMockBuilder('Symfony\Bridge\Doctrine\Form\Type\EntityType')
->disableOriginalConstructor()
->getMock();

$mockEntityType->expects($this->any())->method('getName')
->will($this->returnValue('entity'));

return array(new PreloadedExtension(array(
$mockEntityType->getName() => $mockEntityType,
), array()));
}

public function testSubmitValidData()
{
$formData = array(
'name' => 'Mbalmayo',
'latitude' => 3.5165475,
'longitude' => 11.5144015,
'zoomLevel' => 12.0,
'region' => 'Centre',
);

$type = new CitiesType();
$form = $this->factory->create($type, null);

$object = new Cities();
$object->fromArray($formData);

// submit the data to the form directly
$form->submit($formData);

$this->assertTrue($form->isSynchronized());
$this->assertEquals($object, $form->getData());

$view = $form->createView();
$children = $view->children;

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

此代码基于我之前找到的解决方案。

CitiesType.php

/**
* Builds the form data for the cities
*
* @param FormBuilderInterface $builder The FormBuilderInterface to use
* @param array $options The options for the form, if any
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
/* Several adds that are pointless for this problem */
->add('region', 'entity', array('class' => 'SmopaAgentFinderBundle:Regions',
'property' => 'name',
'required' => true,
'label' => 'city.new.region',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('r')
->orderBy('r.name', 'ASC');
},
'empty_value' => 'Select city\'s region',
'attr' => array('class' => 'new_city_combo_box')
)
);
}

目前,我得到这个错误:

1) FormsTest::testSubmitValidData Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException: The options "attr", "class", "empty_value", "label", "property", "query_builder", "required" do not exist. Known options are: "".

我需要用测试覆盖这些表格,我完全没有想法。有什么帮助吗?

最佳答案

发生这种情况是因为 OptionsResolver 不知道这些选项。您的 EntityType mock 应该声明它们:

对于 Symfony 2.7:

// use Symfony\Component\OptionsResolver\OptionsResolver;

$mockEntityType->method('setDefaultOptions')->will(
$this->returnCallback(
function (OptionsResolver $resolver)
{
$resolver->setDefaults(
array(
'choice_label' => null,
'class' => null,
'query_builder' => null,
'required' => null,
)
);
}
)
);

关于php - 使用实体对 Symfony 表单进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31000421/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com