3
嗨需要一些帮助,联合测试一个Symfony 2.8回调。 我不认为我已经正确设置它为测试路过的时候,我知道,应该没有单元测试Symfony回调
实体设置:
在联系人实体的验证回调:
/**
* 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();
}
}
在联系实体的方法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作为国家代码 '是'是无效的。
可悲的是这也不起作用。传递组作为第二个参数是返回弃用警告:' 有效约束的“深度”选项已从版本2.5开始弃用,并将在3.0中删除。遍历数组时,总是遍历嵌套数组。遍历嵌套对象时,将使用它们的遍历策略: 版本2.5中不推荐使用Symfony \ Component \ Validator \ ValidatorInterface :: validate方法,并且将在版本3.0中将其删除。使用Symfony \ Component \ Validator \ Validator \ ValidatorInterface :: validate方法替代' – pfwd