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
{
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);
$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);
[...]
source
share