Php 如何使用构造函数测试symfony表单类型
我目前正在努力解决Symfony的TypeTestCase问题,用构造函数测试表单类型。虽然将表单注册为服务在应用程序中运行良好,但不能使用TypeTestCase测试相同的表单类型。因为TypeTestCase是从FormIntegrationTestCase扩展而来的,它是从\PHPUnit\u Framework\u TestCase而不是从KernelTestCase扩展而来的。TypeTestCase中的FormFactory不/无法查找注册为服务的表单,并引发调用phpunit的错误:Php 如何使用构造函数测试symfony表单类型,php,symfony,phpunit,symfony-forms,Php,Symfony,Phpunit,Symfony Forms,我目前正在努力解决Symfony的TypeTestCase问题,用构造函数测试表单类型。虽然将表单注册为服务在应用程序中运行良好,但不能使用TypeTestCase测试相同的表单类型。因为TypeTestCase是从FormIntegrationTestCase扩展而来的,它是从\PHPUnit\u Framework\u TestCase而不是从KernelTestCase扩展而来的。TypeTestCase中的FormFactory不/无法查找注册为服务的表单,并引发调用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
我目前看到的唯一方法是不通过构造函数使用configureOptions中的optionsResolver为依赖项提供服务,而是使用setRequired方法为依赖项设置required元素
以下是代码中的相关部分:
DemoType.php
[...]
class DemoType extends AbstractType
{
/**
* @var EntityManager
*/
protected $entityManager;
public function __construct($entityManager)
{
$this->entityManager = $entityManager;
}
[...]
服务.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);
[...]
您可以实例化FormType并将其传递给表单工厂,如中所述 您可以模拟条令实体管理器,例如:
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);
...
关于模拟条令对象堆栈以模拟回购方法的示例,您可以查看或简单询问:)
希望此帮助通过向工厂传递实例化的表单类型而不是类名,不存在弃用警告(从2.8开始,在3.0中删除)?FormFactory::createNamedBuilder触发从2.8开始弃用实例化表单类型的错误:if($type instanceof FormTypeInterface){@trigger\u error(sprintf(“将类型实例传递给FormBuilder::add()、Form::add()或FormFactory自版本2.8以来已被弃用,并且在3.0中不受支持。请改用完全限定的类型类名(%s)。”、get_class($type))、E_USER_弃用);hi@torsten,因此文档与此参数不一致。我将搜索一个以新方式测试表单的示例。如果您发现有用的内容,请告诉我github面临此问题的问题(中)直接:@torsten它并没有解决问题,它只解释了为什么传递实例的可能性被删除了,但没有解释如何在测试中传递依赖项。