Skip to content

Commit 7d8f0b3

Browse files
Rubinumjaviereguiluz
authored andcommitted
Add hint for testing custom constraints
1 parent 486df68 commit 7d8f0b3

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

validation.rst

+43
Original file line numberDiff line numberDiff line change
@@ -801,6 +801,49 @@ You can also validate all the classes stored in a given directory:
801801
802802
$ php bin/console debug:validator src/Entity
803803
804+
Testing Custom Constraints
805+
-------------------------
806+
807+
Since custom constraints contain meaningful logic for your application, writing tests is crucial. You can use the ``ConstraintValidatorTestCase`` to write unit tests for custom constraints:
808+
809+
.. code-block:: php
810+
class IsFalseValidatorTest extends ConstraintValidatorTestCase
811+
{
812+
protected function createValidator()
813+
{
814+
return new IsFalseValidator();
815+
}
816+
817+
public function testNullIsValid()
818+
{
819+
$this->validator->validate(null, new IsFalse());
820+
821+
$this->assertNoViolation();
822+
}
823+
824+
/**
825+
* @dataProvider provideInvalidConstraints
826+
*/
827+
public function testTrueIsInvalid(IsFalse $constraint)
828+
{
829+
$this->validator->validate(true, $constraint);
830+
831+
$this->buildViolation('myMessage')
832+
->setParameter('{{ value }}', 'true')
833+
->setCode(IsFalse::NOT_FALSE_ERROR)
834+
->assertRaised();
835+
}
836+
837+
public function provideInvalidConstraints(): iterable
838+
{
839+
yield 'Doctrine style' => [new IsFalse([
840+
'message' => 'myMessage',
841+
])];
842+
yield 'named parameters' => [new IsFalse(message: 'myMessage')];
843+
}
844+
845+
}
846+
804847
Final Thoughts
805848
--------------
806849

0 commit comments

Comments
 (0)