Php 如何在测试中正确使用Symfony验证器?
我有一个服务班:Php 如何在测试中正确使用Symfony验证器?,php,symfony,validation,mocking,phpunit,Php,Symfony,Validation,Mocking,Phpunit,我有一个服务班: class OutletTableWriter { private $validator; private $entityManager; public function __construct(ValidatorInterface $validator, EntityManagerInterface $em) { $this->validator = $validator; $this->e
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);
}
这正如预期的那样有效。但是,我在测试这个类的功能时遇到了问题。我有以下测试方法:
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());
}
验证器应该失败,因为似乎没有进行验证(返回201响应)。我觉得这与我模仿validator类的方式有关(它甚至需要被模仿吗?-我尝试只传入类本身的一个对象,这导致了以下异常:错误:无法实例化接口Symfony\Component\validator\validator\validator接口
我使用的是Symfony 3.4.6
感谢您的建议。我认为您必须告诉验证器在调用“validate”方法时应该做什么
$errors = ['some_error'];
$validatorMock = $this->createMock(ValidatorInterface::class);
$validatorMock->expects($this->once())->method('validate')->with($outlet)->willReturn($errors);
根据该用户的经验,我让验证器在测试类中工作: 因此,在我的测试中,我做了以下更改(在实例化验证器时):
use Symfony\Component\Validator\Validation;
$this->validator = Validation::createValidatorBuilder()->enableAnnotationMapping()->getValidator();