Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2: Testing entity validation constraints

Tags:

symfony

Does anyone have a good way to unit test an entity's validation constraints in Symfony2?

Ideally I want to have access to the Dependency Injection Container within the unit test which would then give me access to the validator service. Once I have the validator service I can run it manually:

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

I could extend WebTestCase and then create a client to get to the container as per the docs however it doesn't feel right. The WebTestCase and client read in the docs as more of a facility to test actions as a whole and therefore it feels broken to use it to unit test an entity.

So, does anyone know how to either a) get the container or b) create the validator inside a unit test?

like image 562
Kasheen Avatar asked Aug 10 '11 00:08

Kasheen


1 Answers

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 ;).

like image 172
Kasheen Avatar answered Oct 21 '22 04:10

Kasheen