E
E
Elena2018-05-11 19:41:20
symfony
Elena, 2018-05-11 19:41:20

How to properly test entity validation?

Good evening! In the process of mastering unit testing, I came to testing entities and forms. The documentation clearly states that it is not necessary to test the validation in the form, it is necessary to do it directly for the constraints. ( symfony.com/doc/current/form/unit_testing.html).
I wrote such a test, it worked great: test-> test cases-> red strip-> code-> green strip.

<?php

namespace App\Tests\Controller\Admin;

use App\Entity\MyEntity;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\Validation;

/**
 * @group unit
 */
class MyEntityValidationTest extends TestCase
{
    /**
     * @dataProvider getMyEntityInvalidData
     */
    public function testMyEntityIsInvalid($name, $description)
    {
        $validator = Validation::createValidatorBuilder()->enableAnnotationMapping()->getValidator();

        $myEntity = new MyEntity();
        $myEntity->setName($name);
        $myEntity->setDescription($description);
        /** @var ConstraintViolation[] $violations */
        $violations = $validator->validate($myEntity);

        $this->assertTrue(count($violations) == 1);
    }
    public function getMyEntityInvalidData()
    {
        // empty name
        yield ['name' => null, 'description' => 'valid description'];
        // invalid name length
        yield ['name' => '1', 'description' => 'valid description'];
        //invalid name length
        yield [
            'name' => 'qwjdhfnvjcnfhvn nvhf chfn ndnwb nvbchf r nfnefhvn nvjdhf2',
            'description' => 'valid description',
        ];
    }

Then it was necessary to add a uniqueness constraint (Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity), and this is where everything broke down. Doctrine is needed, and more specifically, the error "doctrine.orm.validator.unique' not found" is given. What can be done about it? How best to do to ignore this limitation? Make validation groups? How to remove this restriction from the validator in tests?
Can anyone come across or tell me where to dig?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
voronkovich, 2018-05-11
@voronkovich

This is not unit testing, but integration testing. But forms are much easier to test with functional tests .
An example of working with the form can be seen in the demo application: https://github.com/symfony/demo/blob/96cab4e312a76...
But validation is not tested there. Generally speaking, you are the first person in my memory who does such tests :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question