Skip to content

Commit 72236a2

Browse files
committed
minor #17124 [Validator] Add hint for testing custom constraints (Rubinum)
This PR was submitted for the 6.1 branch but it was merged into the 5.4 branch instead. Discussion ---------- [Validator] Add hint for testing custom constraints <!-- If your pull request fixes a BUG, use the oldest maintained branch that contains the bug (see https://symfony.com/releases for the list of maintained branches). If your pull request documents a NEW FEATURE, use the same Symfony branch where the feature was introduced (and `6.x` for features of unreleased versions). --> I created some custom constraints lately and I stumbled upon the TestCase that symfony developers are using for testing out-of-the-box constraints like IsNull constraints. Since there is no hint in the docs about the ConstraintValidatorTestCase class, I thought it would be a great idea to add this to the docs. This class helped me alot when testing my constraints :) Commits ------- 7d8f0b3 Add hint for testing custom constraints
2 parents 486df68 + 7d8f0b3 commit 72236a2

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)