symfony: adding UniqueEntity Validation to other Constraints trows error in PHPUnit
I use some PHPUnit Validation Test cases for Registration of Users.
Initialization of the Validator looks like this (see also this link):
$this->validator = Validation::createValidatorBuilder()->enableAnnotationMapping()->getValidator();
$errors = $this->validator->validate($user, array(0 => 'registration'));
as soon as I add UniqueEntity constraint to my User entity
@UniqueEntity(fields={"usernameCanonical"}, errorPath="username", message="fos_user.username.already_used", groups={"registration", "profile"})
I get following error when I run the test:
Fatal error: Class ‘doctrine.orm.validator.unique’ not found in mypath\symfony\src\Symfony\Component\Validator\ConstraintValidatorFactory.php on line 33
Maybe I could initialize the Validator separately somehow with
$this->validator = $kernel->getContainer()->get('doctrine.orm.validator.unique');
but then I would have to test the entity constraint after constraint, and couldn’t do it in one line with
$errors = $this->validator->validate($user, array(0 => 'registration'));
is this a bug or am I doing wrong something?
About this issue
- Original URL
- State: closed
- Created 10 years ago
- Reactions: 2
- Comments: 15 (10 by maintainers)
The following solution worked for me:
Getting the validator directly from the container.
@nimasdj , exact same issue here… And we’re in 2022, with Symfony 6.1. The stackoverflow solution doesn’t work anymore.
I try to do a simple unit test but I am getting the ‘doctrine.orm.validator.unique’ not found …
My Entity class “Person” has an
#[UniqueEntity('uniqueId')]attribute. It works everywhere in the app, but with unit-test it fails with the : Error: Class “doctrine.orm.validator.unique” not found 🤷🏻♂️My code :
running in to the same issue, documentation needs to be adjusted here… it’s a pain in the ass working with unit tests in Symfony so far, and it really should not be.
@xabbuh So how is this done inside unit tests? The documentation shows this as the method to get a validator.
So how do you ensure you use the proper factory? That code returns a ValidatorBuilder() but that’s not the ConstraintValidatorFactory.
Really this should just be some information on how to run unit tests with the UniqueEntity constraint. Once someone can point out how this is supposed to work I can commit to providing a PR against the docs.
reading here https://stackoverflow.com/questions/40601866/how-to-configure-dependencies-on-custom-validator-with-symfony-components
I tried to use
ConstraintValidatorFactoryas you suggested, instead of creating a factory as that answer suggests, I did not find the file within framework-bundle folders, please give auseline that I can call it.Btw, why UniqueEntity is not independent from framework like a component as I am getting ‘doctrine.orm.validator.unique’ not found error? I have to add that I have both bundle and doctrine bridge installed.