Symfony2: Testing entity validation constraints

后端 未结 7 1207
南旧
南旧 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 17:13

    Answer (b): Create the Validator inside the Unit Test (Symfony 2.0)

    If you built a Constraint and a ConstraintValidator you don't need any DI container at all.

    Say for example you want to test the Type constraint from Symfony and it's TypeValidator. You can simply do the following:

    use Symfony\Component\Validator\Constraints\TypeValidator;
    use Symfony\Component\Validator\Constraints\Type;
    
    class TypeValidatorTest extends \PHPUnit_Framework_TestCase
    {
      function testIsValid()
      {
        // The Validator class.
        $v = new TypeValidator();
    
        // Call the isValid() method directly and pass a 
        // configured Type Constraint object (options
        // are passed in an associative array).
    
        $this->assertTrue($v->isValid(5, new Type(array('type' => 'integer'))));
        $this->assertFalse($v->isValid(5, new Type(array('type' => 'string'))));
      }
    }
    

    With this you can check every validator you like with any constraint configuration. You neither need the ValidatorFactory nor the Symfony kernel.

    Update: As @psylosss pointed out, this doesn't work in Symfony 2.5. Nor does it work in Symfony >= 2.1. The interface from ConstraintValidator got changed: isValid was renamed to validate and doesn't return a boolean anymore. Now you need an ExecutionContextInterface to initialize a ConstraintValidator which itself needs at least a GlobalExecutionContextInterface and a TranslatorInterface... So basically it's not possible anymore without way too much work.

提交回复
热议问题