Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

symfony2 unit-testing validation with custom validator

I'm trying to write a test for an model which has both some normal validators and a custom validator using an entity manager and the request. I'm using phpunit for my tests if this matters for some reason.

I am testing the custom validator in another test by stubing both the entity manager and the request and then validating some objects. As this proves that the custom validation works, I would only need to test the normal validation and if this is possible simply leave the custom validator out.

Here is my Model:

/**
 * @MyAssert\Client()
 */
abstract class BaseRequestModel {

    /**
     * @Assert\NotBlank(message="2101")
     */
    protected $clientId;

    /**
     * @Assert\NotBlank(message="2101")
     */
    protected $apiKey;

    // ...

}

In my test, I'm getting the validator, creating an object and then validating it.

$validator = ValidatorFactory::buildDefault()->getValidator();
$requestModel = new RequestModel();
$errors = $validator->validate($requestModel);

Of course this fails as it cannot find the Validator defined for MyAssert\Client, which is a service and needs to be resolved by some dependency injection container.

Anyone has any idea how to either stub the custom validator or to exclude it from validation?

like image 262
Sgoettschkes Avatar asked Feb 09 '12 10:02

Sgoettschkes


2 Answers

I'd go with something like that:

class MyTest extends Symfony\Bundle\FrameworkBundle\Test\WebTestCase
{
    private function getKernel()
    {
        $kernel = $this->createKernel();
        $kernel->boot();

        return $kernel;
    }

    public function testCustomValidator()
    {
        $kernel = $this->getKernel();
        $validator = $kernel->getContainer()->get('validator');

        $violationList = $validator->validate(new RequestModel);

        $this->assertEquals(1, $violationList->count());
        // or any other like:
        $this->assertEquals('client not valid', $violationList[0]->getMessage());
    }
}
like image 188
Florian Klein Avatar answered Nov 17 '22 22:11

Florian Klein


have you tried this?

$validator = Validation::createValidatorBuilder()->enableAnnotationMapping()->getValidator();
like image 33
Andrej Sramko Avatar answered Nov 17 '22 21:11

Andrej Sramko