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
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
ConstraintValidatorgot changed:isValidwas renamed tovalidateand doesn't return a boolean anymore. Now you need anExecutionContextInterfaceto initialize aConstraintValidatorwhich itself needs at least aGlobalExecutionContextInterfaceand aTranslatorInterface... So basically it's not possible anymore without way too much work.