Validating symfony2 unit testing with a custom validator

I am trying to write a test for a model that has both some regular validators and a custom validator using the entity manager and query. I use phpunit for my tests if this is for some reason.

I am testing a custom validator in another test, drowning out both the entity manager and the request, and then checking some objects. Since this proves that custom validation works, I will only need to validate the normal validation, and if possible just leave the custom validator.

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 get a validator, create an object and validate it.

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

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

Does anyone know how to block a custom validator or exclude it from the scan ?

+6
source share
2 answers

I would say something like this:

 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()); } } 
+6
source

Have you tried this?

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

Source: https://habr.com/ru/post/908030/


All Articles