Skip to content

Commit 4900291

Browse files
javiereguiluzwouterj
authored andcommitted
[Validator] Add hint for testing custom constraints
1 parent 83d0d4d commit 4900291

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

validation/custom_constraint.rst

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -272,3 +272,46 @@ not to the property:
272272
$metadata->addConstraint(new ProtocolClass());
273273
}
274274
}
275+
276+
Testing Custom Constraints
277+
--------------------------
278+
279+
Use the ``ConstraintValidatorTestCase`` utility to simplify the creation of
280+
unit tests for your custom constraints::
281+
282+
// ...
283+
use App\Validator\ContainsAlphanumeric;
284+
use App\Validator\ContainsAlphanumericValidator;
285+
286+
class ContainsAlphanumericValidatorTest extends ConstraintValidatorTestCase
287+
{
288+
protected function createValidator()
289+
{
290+
return new ContainsAlphanumericValidator();
291+
}
292+
293+
public function testNullIsValid()
294+
{
295+
$this->validator->validate(null, new ContainsAlphanumeric());
296+
297+
$this->assertNoViolation();
298+
}
299+
300+
/**
301+
* @dataProvider provideInvalidConstraints
302+
*/
303+
public function testTrueIsInvalid(ContainsAlphanumeric $constraint)
304+
{
305+
$this->validator->validate('...', $constraint);
306+
307+
$this->buildViolation('myMessage')
308+
->setParameter('{{ string }}', '...')
309+
->assertRaised();
310+
}
311+
312+
public function provideInvalidConstraints(): iterable
313+
{
314+
yield [new ContainsAlphanumeric(message: 'myMessage')];
315+
// ...
316+
}
317+
}

0 commit comments

Comments
 (0)