How to Unit Test your Forms

How to Unit Test your Forms

Caution

This article is intended for developers who create custom form types. If you are using the built-in Symfony form types or the form types provided by third-party bundles, you don’t need to unit test them.

The Form component consists of 3 core objects: a form type (implementing Symfony\Component\Form\FormTypeInterface), the Symfony\Component\Form\Form and the Symfony\Component\Form\FormView.

The only class that is usually manipulated by programmers is the form type class which serves as a form blueprint. It is used to generate the Form and the FormView. You could test it directly by mocking its interactions with the factory but it would be complex. It is better to pass it to FormFactory like it is done in a real application. It is easier to bootstrap and you can trust the Symfony components enough to use them as a testing base.

There is already a class that you can benefit from for testing: Symfony\Component\Form\Test\TypeTestCase. It is used to test the core types and you can use it to test your types too.

Note

Depending on the way you installed your Symfony or Symfony Form component the tests may not be downloaded. Use the --prefer-source option with Composer if this is the case.

The Basics

The simplest TypeTestCase implementation looks like the following:

  1. // tests/Form/Type/TestedTypeTest.php
  2. namespace App\Tests\Form\Type;
  3. use App\Form\Type\TestedType;
  4. use App\Model\TestObject;
  5. use Symfony\Component\Form\Test\TypeTestCase;
  6. class TestedTypeTest extends TypeTestCase
  7. {
  8. public function testSubmitValidData()
  9. {
  10. $formData = [
  11. 'test' => 'test',
  12. 'test2' => 'test2',
  13. ];
  14. $model = new TestObject();
  15. // $formData will retrieve data from the form submission; pass it as the second argument
  16. $form = $this->factory->create(TestedType::class, $model);
  17. $expected = new TestObject();
  18. // ...populate $object properties with the data stored in $formData
  19. // submit the data to the form directly
  20. $form->submit($formData);
  21. // This check ensures there are no transformation failures
  22. $this->assertTrue($form->isSynchronized());
  23. // check that $formData was modified as expected when the form was submitted
  24. $this->assertEquals($expected, $model);
  25. }
  26. public function testCustomFormView()
  27. {
  28. $formData = new TestObject();
  29. // ... prepare the data as you need
  30. // The initial data may be used to compute custom view variables
  31. $view = $this->factory->create(TestedType::class, $formData)
  32. ->createView();
  33. $this->assertArrayHasKey('custom_var', $view->vars);
  34. $this->assertSame('expected value', $view->vars['custom_var']);
  35. }
  36. }

So, what does it test? Here comes a detailed explanation.

First you verify if the FormType compiles. This includes basic class inheritance, the buildForm() function and options resolution. This should be the first test you write:

  1. $form = $this->factory->create(TestedType::class, $formData);

This test checks that none of your data transformers used by the form produces an error. The [isSynchronized()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Form/FormInterface.php "Symfony\Component\Form\FormInterface::isSynchronized()") method is only set to false if a data transformer throws an exception:

  1. $form->submit($formData);
  2. $this->assertTrue($form->isSynchronized());

Note

Don’t test the validation: it is applied by a listener that is not active in the test case and it relies on validation configuration. Instead, unit test your custom constraints directly or read how to add custom extensions in the last section of this page.

Next, verify the submission and mapping of the form. The test below checks if all the fields are correctly specified:

  1. $this->assertEquals($expected, $formData);

Finally, check the creation of the FormView. You can check that a custom variable exists and will be available in your form themes:

  1. $this->assertArrayHasKey('custom_var', $view->vars);
  2. $this->assertSame('expected value', $view->vars['custom_var']);

Tip

Use PHPUnit data providers to test multiple form conditions using the same test code.

Caution

When your type relies on the EntityType, you should register the Symfony\Bridge\Doctrine\Form\DoctrineOrmExtension, which will need to mock the ManagerRegistry.

However, If you cannot use a mock to write your test, you should extend the KernelTestCase instead and use the form.factory service to create the form.

Testings Types Registered as Services

Your form may be used as a service, as it depends on other services (e.g. the Doctrine entity manager). In these cases, using the above code won’t work, as the Form component instantiates the form type without passing any arguments to the constructor.

To solve this, you have to mock the injected dependencies, instantiate your own form type and use the Symfony\Component\Form\PreloadedExtension to make sure the FormRegistry uses the created instance:

  1. // tests/Form/Type/TestedTypeTest.php
  2. namespace App\Tests\Form\Type;
  3. use App\Form\Type\TestedType;
  4. use Doctrine\Persistence\ObjectManager;
  5. use Symfony\Component\Form\PreloadedExtension;
  6. use Symfony\Component\Form\Test\TypeTestCase;
  7. // ...
  8. class TestedTypeTest extends TypeTestCase
  9. {
  10. private $objectManager;
  11. protected function setUp(): void
  12. {
  13. // mock any dependencies
  14. $this->objectManager = $this->createMock(ObjectManager::class);
  15. parent::setUp();
  16. }
  17. protected function getExtensions()
  18. {
  19. // create a type instance with the mocked dependencies
  20. $type = new TestedType($this->objectManager);
  21. return [
  22. // register the type instances with the PreloadedExtension
  23. new PreloadedExtension([$type], []),
  24. ];
  25. }
  26. public function testSubmitValidData()
  27. {
  28. // ...
  29. // Instead of creating a new instance, the one created in
  30. // getExtensions() will be used.
  31. $form = $this->factory->create(TestedType::class, $formData);
  32. // ... your test
  33. }
  34. }

Adding Custom Extensions

It often happens that you use some options that are added by form extensions. One of the cases may be the ValidatorExtension with its invalid_message option. The TypeTestCase only loads the core form extension, which means an Symfony\Component\OptionsResolver\Exception\InvalidOptionsException will be raised if you try to test a class that depends on other extensions. The [getExtensions()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Form/Test/TypeTestCase.php "Symfony\Component\Form\Test\TypeTestCase::getExtensions()") method allows you to return a list of extensions to register:

  1. // tests/Form/Type/TestedTypeTest.php
  2. namespace App\Tests\Form\Type;
  3. // ...
  4. use Symfony\Component\Form\Extension\Validator\ValidatorExtension;
  5. use Symfony\Component\Validator\Validation;
  6. class TestedTypeTest extends TypeTestCase
  7. {
  8. protected function getExtensions()
  9. {
  10. $validator = Validation::createValidator();
  11. // or if you also need to read constraints from annotations
  12. $validator = Validation::createValidatorBuilder()
  13. ->enableAnnotationMapping()
  14. ->getValidator();
  15. return [
  16. new ValidatorExtension($validator),
  17. ];
  18. }
  19. // ... your tests
  20. }

Note

By default only the Symfony\Component\Form\Extension\Core\CoreExtension is registered in tests. You can find other extensions from the Form component in the Symfony\Component\Form\Extension namespace.

It is also possible to load custom form types, form type extensions or type guessers using the [getTypes()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Form/Test/FormIntegrationTestCase.php "Symfony\Component\Form\Test\FormIntegrationTestCase::getTypes()"), [getTypeExtensions()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Form/Test/FormIntegrationTestCase.php "Symfony\Component\Form\Test\FormIntegrationTestCase::getTypeExtensions()") and [getTypeGuessers()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Form/Test/FormIntegrationTestCase.php "Symfony\Component\Form\Test\FormIntegrationTestCase::getTypeGuessers()") methods.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.