Testez unitairement un validateur personnalisé Symfony avec le cas de test ConstraintValidatorTestCase

Publié le 06/11/2022 • Actualisé le 06/11/2022


English language detected! 🇬🇧

  We noticed that your browser is using English. Do you want to read this post in this language?

Read the english version 🇬🇧 Close

Dans ce bout de code, nous voyons comment tester unitairement un validateur personnalisé Symfony avec le cas de test ConstraintValidatorTestCase. Dans le précédent snippet, nous avons vu comment faire cela manuellement. Cette fois, nous utilisons le cas de test ConstraintValidatorTestCase. Ça fonctionne bien puisque le code final du test est plus concis, et l'on n'a pas à écrire de mock soi-même comme Symfony gère cela pour nous.


<?php

declare(strict_types=1);

namespace App\Tests\Unit\Validator;

use App\Entity\Article;
use App\Validator\NotCoil;
use App\Validator\NotCoilValidator;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;

/**
 * @extends ConstraintValidatorTestCase<NotCoilValidator>
 */
final class NotCoilWithConstraintValidatorTest extends ConstraintValidatorTestCase
{
    protected function createValidator(): NotCoilValidator
    {
        return new NotCoilValidator();
    }

    /**
     * @return iterable<int, array{0: ?string}>
     */
    public function provideIsValid(): iterable
    {
        yield ['Foobar'];
        yield [''];
        yield [null];
    }

    /**
     * @dataProvider provideIsValid
     */
    public function testIsValid(?string $value): void
    {
        $this->validator->validate($value, new NotCoil());
        $this->assertNoViolation();
    }

    public function testIsInvalid(): void
    {
        $this->validator->validate('COil', new NotCoil());
        $this->buildViolation('The value should not be COil')->assertRaised();
    }

    public function testInvalidValueType(): void
    {
        $this->expectException(UnexpectedValueException::class);
        $this->validator->validate(new Article(), new NotCoil());
    }

    public function testInvalidConstraintType(): void
    {
        $this->expectException(UnexpectedTypeException::class);
        $this->validator->validate('foo', new Length(['max' => 5]));
    }
}

 Plus sur Stackoverflow   Lire la doc  Snippet aléatoire

  Travaillez avec moi !