Reputation: 13189
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?
Upvotes: 6
Views: 3604
Reputation: 833
have you tried this?
$validator = Validation::createValidatorBuilder()->enableAnnotationMapping()->getValidator();
Upvotes: 3
Reputation: 8915
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());
}
}
Upvotes: 6