You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
Copy file name to clipboardExpand all lines: validation.rst
+43
Original file line number
Diff line number
Diff line change
@@ -801,6 +801,49 @@ You can also validate all the classes stored in a given directory:
801
801
802
802
$ php bin/console debug:validator src/Entity
803
803
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
0 commit comments