2016-11-05 161 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