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