如何在测试中正确使用 Symfony 验证器?

Mr *_*r B 2 php validation phpunit mocking symfony

我有一个服务类:

class OutletTableWriter
{
    private $validator;

    private $entityManager;

    public function __construct(ValidatorInterface $validator, EntityManagerInterface $em)
    {
        $this->validator    = $validator;
        $this->em           = $em;

    }
// inserts outlet to db
    public function insertOutlet($outletName, $buildingName = null, $propertyNumber, $streetName, $area, $town, $contactNumber, $postcode)
    {
        $outlet = new Outlet();
        $outlet->setOutletName($outletName);
        $outlet->setBuildingName($buildingName);
        $outlet->setPropertyNumber($propertyNumber);
        $outlet->setStreetName($streetName);
        $outlet->setArea($area);
        $outlet->setTown($town);
        $outlet->setContactNumber($contactNumber);
        $outlet->setPostCode($postcode);
        $outlet->setIsActive(0);

        // $validator = $this->get('validator'); // validate constraints
        $errors = $this->validator->validate($outlet);
        if (count($errors) > 0) {
            $response = new Response('', 422, array('content-type' => 'text/html'));

            $errorsString = (string) $errors;
            $response->setContent($errorsString);
            return $response;
        }

        $this->em->persist($outlet);
        $this->em->flush(); // save

        return new Response('Outlet #'.$outlet->getId().' has been successfully saved.', 201);
    }
Run Code Online (Sandbox Code Playgroud)

这按预期工作。但是,我在测试此类的功能时遇到了问题。我有以下测试方法:

public function testUnsuccessfulInsertOutlet()
    {
        $mockValidator  = $this->getMockBuilder(ValidatorInterface::class)
            ->disableOriginalConstructor()
            ->getMock();

        $mockEm         = $this->getMockBuilder(EntityManagerInterface::class)
            ->disableOriginalConstructor()->getMock();


        $outletTableWriter  = new OutletTableWriter($mockValidator, $mockEm);
        $response           = $outletTableWriter->insertOutlet(
            '', '', '', '', '', '', 'EXX 1XX'
        );

        $this->assertEquals(422, $response->getStatusCode());
    }
Run Code Online (Sandbox Code Playgroud)

验证器应该失败,而不是看起来没有完成验证(返回 201 响应)。我觉得它与我模拟验证器类的方式有关(它甚至需要被模拟吗? - 我尝试只传递类本身的一个对象,这导致了以下异常:Error: Cannot instantiate interface Symfony\Component\Validator\Validator\ValidatorInterface

我正在使用 Symfony 3.4.6。

感谢任何建议。

Mr *_*r B 8

根据该用户的经验,我让验证器在测试类中工作:https://github.com/symfony/symfony-docs/issues/6532

因此,在我的测试中,我做了以下更改(实例化验证器时):

use Symfony\Component\Validator\Validation;

$this->validator    = Validation::createValidatorBuilder()->enableAnnotationMapping()->getValidator();
Run Code Online (Sandbox Code Playgroud)