单元测试Symfony回调

时间:2016-11-05 09:27:38

标签: validation unit-testing symfony callback phpunit

您需要一些帮助来联合测试Symfony 2.8回调。 当我知道它应该失败时,我认为我没有正确设置,因为测试正在通过

实体设置:

联系人实体中的验证回调:

 /**
 * 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但由于国家/地区代码“IS”无效,因此应为1。

1 个答案:

答案 0 :(得分:3)

第一个问题是关于yml文件中约束的定义:您需要将callback放在constraint部分而不是properties下,所以更改validation.yml文件如下:

validation.yml

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

第二:您需要从容器中获取验证器服务,而不是使用构建器创建新服务:此对象未使用对象结构ect初始化。

第三次仅为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));
    }

测试用例变成了绿色。

希望这个帮助

相关问题