Validation in Symfony2 unit tests

Want to use the Validation module in your Symfony2 unit tests? No problem, thanks to the ValidatorFactory, it’s relatively straight forward.

use Symfony\Component\Validator\ValidatorFactory;

class ExampleTest extends \PHPUnit_Framework_TestCase
{
    public function testSomething()
    {
        $validator = ValidatorFactory::buildDefault()->getValidator();
    }
}

Simply include the ValidatorFactory namespace and then use the class and it’s default values method to deliver you a validator, which you can then validate your objects against just as if it was in a controller.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.