Symfony2: Testing entity validation constraints

后端 未结 7 1208
南旧
南旧 2020-12-07 16:35

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

7条回答
  •  感动是毒
    2020-12-07 16:59

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

提交回复
热议问题