Skip to content

[Validator] Add hint for testing custom constraints #17124

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 9, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions validation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -801,6 +801,49 @@ You can also validate all the classes stored in a given directory:

$ php bin/console debug:validator src/Entity

Testing Custom Constraints
-------------------------

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:

.. code-block:: php
class IsFalseValidatorTest extends ConstraintValidatorTestCase
{
protected function createValidator()
{
return new IsFalseValidator();
}

public function testNullIsValid()
{
$this->validator->validate(null, new IsFalse());

$this->assertNoViolation();
}

/**
* @dataProvider provideInvalidConstraints
*/
public function testTrueIsInvalid(IsFalse $constraint)
{
$this->validator->validate(true, $constraint);

$this->buildViolation('myMessage')
->setParameter('{{ value }}', 'true')
->setCode(IsFalse::NOT_FALSE_ERROR)
->assertRaised();
}

public function provideInvalidConstraints(): iterable
{
yield 'Doctrine style' => [new IsFalse([
'message' => 'myMessage',
])];
yield 'named parameters' => [new IsFalse(message: 'myMessage')];
}

}

Final Thoughts
--------------

Expand Down