2016-11-05 276 views
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

首先问题是关于在YML文件约束的定义是:你需要把callbackconstraint部分代替properties,所以更改validation.yml文件如下:

验证.yml

AppBundle\Entity\Contact: 
    constraints: 
     - Callback: 
      callback: [ AppBundle\Entity\Contact, validate ] 
      groups: [ "AppBundle" ] 

在测试用例二:你需要从容器instea验证服务用构建器创建一个新对象:这个对象没有用对象结构等初始化。

第三仅为AppBundle验证组定义了回调约束,因此将验证组传递给验证器服务(作为服务的第三个参数)。

所以改变的TestClass如下:

public function testValidate() 
    { 
     $country = new Country(); 
     $country->setCode('IS'); 

     $contact = new Contact(); 
     $contact->setCountry($country); 

//  $validator = Validation::createValidatorBuilder()->getValidator(); 
     $validator = $this->createClient()->getContainer()->get('validator'); 

     $errors = $validator->validate($contact, null, ['AppBundle']); 
     $this->assertEquals(1, count($errors)); 
    } 

而且测试用例成了绿色。

希望这个帮助

+0

可悲的是这也不起作用。传递组作为第二个参数是返回弃用警告:' 有效约束的“深度”选项已从版本2.5开始弃用,并将在3.0中删除。遍历数组时,总是遍历嵌套数组。遍历嵌套对象时,将使用它们的遍历策略: 版本2.5中不推荐使用Symfony \ Component \ Validator \ ValidatorInterface :: validate方法,并且将在版本3.0中将其删除。使用Symfony \ Component \ Validator \ Validator \ ValidatorInterface :: validate方法替代' – pfwd