Unit testing of a Symfony custom constraint with the ConstraintValidatorTestCase

Published on 2022-11-06 • Modified on 2022-11-06

This snippet shows how to unit test a Symfony custom constraint with the ConstraintValidatorTestCase. In the previous snippet, we see how to do this manually. This time, we use the ConstraintValidatorTestCase. It works well as the final test is more concise, and you don't have to write any mock by yourself, as Symfony already does this for you.


<?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]));
    }
}

 More on Stackoverflow   Read the doc  Random snippet

  Work with me!