Symfony2: Testing entity validation constraints

Ok since this got two votes I guess other people are interested.

I decided to get my shovel out and was pleasantly surprised (so far anyway) that this wasn’t at all difficult to pull off.

I remembered that each Symfony2 component can be used in a stand alone mode and therefore that I could create the validator myself.

Looking at the docs at: https://github.com/symfony/Validator/blob/master/ValidatorFactory.php

I realised that since there was a ValidatorFactory it was trivial to create a validator (especially for validation done by annotations which I am, although if you look at the docblock on the page I linked above you’ll also find ways to validate xml and yml).

First:

# Symfony >=2.1
use Symfony\Component\Validator\Validation;
# Symfony <2.1
use Symfony\Component\Validator\ValidatorFactory;

and then:

# Symfony >=2.1
$validator = Validation::createValidatorBuilder()->enableAnnotationMapping()->getValidator();
# Symfony <2.1
$validator = ValidatorFactory::buildDefault()->getValidator();

$errors = $validator->validate($entity);

$this->assertEquals(0, count($errors));

I hope this helps anyone else whose conscience wouldn’t allow them to just use WebTestCase ;).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)