Search code examples
symfonysymfony-formssymfony4

How to unit test entity assert in Symfony form?


With Symfony 4.2, I have entity with assert :

...
/**
 * @var string
 *
 * @Assert\NotBlank()
 * @Assert\Email()
 */
private $email;
...

I have a form for this entity :

$builder
    ...
    ->add('email', null, [
        'label' => 'label.email',
        'help' => 'email.help_privacy',
    ])
    ...

I want to test this form. I read the doc : How to Unit Test your Forms

But when I want to test this form, But I don't know how to test asserts. Here the email is not completed while I have a Notblank() assert.

public function testSubmitValidData(): void
{
    $formData = [
        'name' => 'Sheriff Woody',
        'message' => 'Hello Sheriff Woody',
    ];

    $objectToCompare = new Contact();

    $form = $this->factory->create(ContactType::class, $objectToCompare);

    $object = new Contact();
    $object->setName('Sheriff Woody');
    $object->setMessage('Hello Sheriff Woody');

    $form->submit($formData);

    $this->assertTrue($form->isSynchronized());

    $this->assertEquals(
        $object,
        $objectToCompare
    );

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

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

But I do not know how to test the asserts of my entity. Can you help me ?


Solution

  • Disclaimer: I usually use functional tests to test my form rather than unit tests.

    The assert part is not really form, it's validation. You can test it separately (as you choose TU over TF).

    Your problem is documented in the documentation:

    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.

    Personally, I don't really see the point of unit testing a form for a small/medium project as we can safely assume that the form factory of Symfony works well.