Mocking custom constraints in test where the constraints are used

I have a class that injects symfony’s validator (and other services) and then uses that validator with some custom constraints. These custom constraints have their own dependencies, including accessing the DB through Repository classes.

I have successfully mocked the construction of the class, but the custom constraints rely on lazy loading or something and are constructed on demand. The custom constraints require DB access which I would like to mock so they can run without true DB access.

How do I control/mock the construction of the custom constraints in my test? In the example below, I would like to mock ValidOne and ValidTwo.

for example:

class Foo
{
   private $validator;

   public function validateBar(array $bar)
   {
       return $this->validator->Validator($bar, new ConstraintsCollection([
           'one' => ValidOne(), // custom constraint requires DB access
           'two' => ValidTwo()
       ]);
    }
}
class FooTest extends KernelTestCase
{
    protected function testValidateBar()
    {
        $validator = Validation::createValidator();
        $foo = new Foo($validator);
        $bar = ['one' => 1, 'two' => 2];
        $errors = $foo->validateBar($bar);
        $this->assertEquals(0, count($errors));
    }
}

Source: Symfony Questions

LEAVE A COMMENT