Testez unitairement un validateur personnalisé Symfony avec le cas de test ConstraintValidatorTestCase
Publié le 06/11/2022 • Actualisé le 06/11/2022
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
A vous de jouer !
Ces articles vous ont été utiles ? Vous pouvez m'aider à votre tour de plusieurs manières : (cliquez sur le lien "reply" dans à droite pour me contacter )
- Me remonter des erreurs ou typos.
- Me remonter des choses qui pourraient être améliorées.
- Aimez et repostez !
- Suivez moi sur Bluesky 🦋
- Inscrivez-vous au flux RSS.
- Cliquez sur les boutons Plus sur Stackoverflow pour me faire gagner des badges "annonceur" 🏅.
Merci et à très bientôt sur Strangebuzz ! 😉
