【发布时间】:2017-03-19 02:41:48
【问题描述】:
您好,在联合测试 Symfony 2.8 回调方面需要一些帮助。 我认为我没有正确设置它,因为当我知道它应该失败时测试通过了
实体设置:
Contact 实体中的验证回调:
/**
* Validation callback for contact
* @param \AppBundle\Entity\Contact $object
* @param ExecutionContextInterface $context
*/
public static function validate(Contact $object, ExecutionContextInterface $context)
{
/**
* Check if the country code is valid
*/
if ($object->isValidCountryCode() === false) {
$context->buildViolation('Cannot register in that country')
->atPath('country')
->addViolation();
}
}
Contact实体中的方法isValidCountryCode:
/**
* Get a list of invalid country codes
* @return array Collection of invalid country codes
*/
public function getInvalidCountryCodes()
{
return array('IS');
}
检查国家代码是否无效的方法:
/**
* Check if the country code is valid
* @return boolean
*/
public function isValidCountryCode()
{
$invalidCountryCodes = $this->getInvalidCountryCodes();
if (in_array($this->getCountry()->getCode(), $invalidCountryCodes)) {
return false;
}
return true;
}
validation.yml
AppBundle\Entity\Contact:
properties:
//...
country:
//..
- Callback:
callback: [ AppBundle\Entity\Contact, validate ]
groups: [ "AppBundle" ]
测试类:
//..
use Symfony\Component\Validator\Validation;
class CountryTest extends WebTestCase
{
//...
public function testValidate()
{
$country = new Country();
$country->setCode('IS');
$contact = new Contact();
$contact->setCountry($country);
$validator = Validation::createValidatorBuilder()->getValidator();
$errors = $validator->validate($contact);
$this->assertEquals(1, count($errors));
}
此测试返回 $errors,计数为 0,但应为 1,因为国家代码“IS”无效。
【问题讨论】:
标签: validation unit-testing symfony callback phpunit