50

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?

2
  • I'm not really sure which post to choose as the answer below since I think both are correct. I'll tick my own (if no one objects) since it focuses in on just the validator but Matt's answer allows for the whole DIC which could be useful for some people (and I had mentioned it in the original question).
    – Kasheen
    Aug 10, 2011 at 19:57
  • Choose any of the two answers, there is no problem :) I'm glad if it can help anyone else and also happy that you did solve your problem :)
    – Matt
    Aug 11, 2011 at 15:06

8 Answers 8

69

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

5
  • 29
    ValidatorFactory is deprecated in Symfony 2.1. You can replace it with Validation::createValidatorBuilder()->enableAnnotationMapping()->getValidator() if you are using annotations.
    – g .
    Oct 28, 2012 at 9:28
  • Thanks for that update, its true that this answer has become out-dated with Symfony2.1 to some extent.
    – Kasheen
    Nov 1, 2012 at 23:20
  • Not all services are so easily constructable - they might need another services or (possibly processed config variables). IMO better would be use container.
    – JohnSmith
    Aug 6, 2015 at 9:15
  • For Symfony 4.2, just replace the assertion by $this->assertEquals(0, $errors->count());
    – Baudev
    Mar 8, 2019 at 17:52
  • Same for Symfony 5.1. Use Validation::createValidatorBuilder()->enableAnnotationMapping()->getValidator(); otherwise the annotations will not validate.
    – klodoma
    Jun 29, 2020 at 14:36
38

We end up rolling your own base test case to access the dependency container from within a test case. Here the class in question:

<?php

namespace Application\AcmeBundle\Tests;

// This assumes that this class file is located at:
// src/Application/AcmeBundle/Tests/ContainerAwareUnitTestCase.php
// with Symfony 2.0 Standard Edition layout. You may need to change it
// to fit your own file system mapping.
require_once __DIR__.'/../../../../app/AppKernel.php';

class ContainerAwareUnitTestCase extends \PHPUnit_Framework_TestCase
{
    protected static $kernel;
    protected static $container;

    public static function setUpBeforeClass()
    {
        self::$kernel = new \AppKernel('dev', true);
        self::$kernel->boot();

        self::$container = self::$kernel->getContainer();
    }

    public function get($serviceId)
    {
        return self::$kernel->getContainer()->get($serviceId);
    }
}

With this base class, you can now do this in your test methods to access the validator service:

$validator = $this->get('validator');

We decided to go with a static function instead of the class constructor but you could easily change the behavior to instantiate the kernel into the constructor directly instead of relying on the static method setUpBeforeClass provided by PHPUnit.

Also, keep in mind that each single test method in you test case won't be isolated fro, each others because the container is shared for the whole test case. Making modification to the container may have impact on you other test method but this should not be the case if you access only the validator service. However, this way, the test cases will run faster because you will not need to instantiate and boot a new kernel for each test methods.

For the sake of reference, we find inspiration for this class from this blog post. It is written in French but I prefer to give credit to whom it belongs :)

Regards,
Matt

5
  • Ah fantastic! Thank you for your reply - this popped up by ajax as I was writing mine below, helps if I refresh my page first ;). This looks like a good solution also, especially if you need to access more than just the validator on the container. Also you bring up a good point in my code below whereby the validator could be held as an instance variable instead of being re-created for each test method for performance sake. Thank you again! :)
    – Kasheen
    Aug 10, 2011 at 19:51
  • 4
    Note that booting the whole kernel can be heavy and may slow down your tests considerably. Use with caution.
    – wdev
    Jan 8, 2013 at 10:42
  • For me, the class needs to be declared abstract, otherwise PHPUnit thinks it is a test class (even if I move it out of the Tests directory and remove Test from the name – I assume this is because it extends PHPUnit_Framework_TestCase...)
    – Tim
    May 30, 2014 at 12:21
  • @Tim it's probably because of missing/incorrect PHPUnit configuration: symfony.com/doc/current/book/testing.html#phpunit-configuration
    – Wirone
    Sep 2, 2014 at 8:33
  • Symfony 3 : A new class has been created for such tests : the KernelTestCase
    – Xapadoan
    Jan 12, 2018 at 0:19
28

I liked Kasheens answer, but it doesn't work for Symfony 2.3 anymore. There are little changes:

use Symfony\Component\Validator\Validation;

and

$validator = Validation::createValidatorBuilder()->getValidator();

If you want to validate Annotations for instance, use enableAnnotationMapping() like below:

$validator = Validation::createValidatorBuilder()->enableAnnotationMapping()->getValidator();

the rest stays the same:

$errors = $validator->validate($entity);
$this->assertEquals(0, count($errors));
2
  • 1
    Official usage link github.com/symfony/Validator/blob/master/README.md#usage ; use Symfony\Component\Validator\Validation; use Symfony\Component\Validator\Constraints\Length; $validator = Validation::createValidator(); $violations = $validator->validateValue('Bernhard', new Length(array('min' => 10)));
    – Mikl
    Jun 4, 2014 at 18:53
  • 2
    I really don't know why this is not shown in the official Unit Testing documentation for Symfony Forms! Thank you for pointing out this solution.
    – tftd
    Apr 4, 2015 at 23:32
7

With Symfony 2.8, it seems that you can now use the AbstractConstraintValidatorTest class this way :

<?php
namespace AppBundle\Tests\Constraints;

use Symfony\Component\Validator\Tests\Constraints\AbstractConstraintValidatorTest;
use AppBundle\Constraints\MyConstraint;
use AppBundle\Constraints\MyConstraintValidator;
use AppBundle\Entity\MyEntity;
use Symfony\Component\Validator\Validation;

class MyConstraintValidatorTest extends AbstractConstraintValidatorTest
{
    protected function getApiVersion()
    {
        return Validation::API_VERSION_2_5;
    }

    protected function createValidator()
    {
        return new MyConstraintValidator();
    }

    public function testIsValid()
    {
        $this->validator->validate(null, new MyEntity());

        $this->assertNoViolation();
    }

    public function testNotValid()
    {
        $this->assertViolationRaised(new MyEntity(), MyConstraint::SOME_ERROR_NAME);
    }
}

You have got a good sample with the IpValidatorTest class

1
  • 1
    Little typo in the first use. Should be Tests instead of Test
    – Cassiano
    Sep 19, 2017 at 18:34
5

The answer in https://stackoverflow.com/a/41884661/4560833 has to be changed a little for Symfony 4:

Use ConstraintValidatorTestCase instead of AbstractConstraintValidatorTest.

2

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.

2
  • It results Call to undefined method Symfony\Component\Validator\Constraints\TypeValidator::isValid() in symfony 2.5
    – psylosss
    Mar 10, 2015 at 9:35
  • @psylosss You're right. Apparently the ConstraintValidator interface got changed from Symfony 2.0 (where this answer originates from) to Symfony 2.1. See GitHub commit.
    – flu
    Mar 11, 2015 at 13:53
0

I don't see a problem with the WebTestCase. If you don't want a client, don't create one ;) But using a possibly different service than your actual application will use, that's a potential pit fall. So personally, I've done like this:

class ProductServiceTest extends Symfony\Bundle\FrameworkBundle\Test\WebTestCase
{

    /**
     * Setup the kernel.
     *
     * @return null
     */
    public function setUp()
    {
        $kernel = self::getKernelClass();

        self::$kernel = new $kernel('dev', true);
        self::$kernel->boot();
    }

    public function testFoo(){
        $em = self::$kernel->getContainer()->get('doctrine.orm.entity_manager');
        $v  = self::$kernel->getContainer()->get('validator');

        // ...
    }

}

It's less DRY than Matt answer -- as you'll repeat the code (for each test class) and boot the kernel often (for each test method), but it's self-contained and require no extra dependencies, so it depends on your needs. Plus I got rid of the static require.

Also, you're sure to have the same services that your application is using -- not default or mock, as you boot the kernel in the environnement that you wish to test.

0

If people still read this one in 2023, prefer to inject the ValidatorInterface for Symfony > 3 / 4.

use Symfony\Component\Validator\Validator\ValidatorInterface;

// ...

$this->validator->validate($myEntity);
3
  • But how do you inject it in a test case class ?
    – Xmanoux
    Jan 31, 2023 at 17:41
  • Using the getContainer, you can have it like : $this->validator = static::$kernel->getContainer()->get('validator'); in your setUp method Jan 31, 2023 at 23:04
  • It unfortunately doesn't work with sf6+, validator service is not loaded anymore in test kernel. They say it's part of the container optimisation features... The (exotic) solution is to define a public alias for validator...
    – Xmanoux
    Feb 1, 2023 at 14:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.