使用symfony2.3对单元测试验证器约束

时间:2014-10-24 14:55:06

标签: php unit-testing symfony phpunit symfony-validator

我想使用约束制作一个测试单元,但在运行测试时出现此错误

这是我的不同类以及运行phpunit后获取错误



use Symfony\Component\Validator\Constraint;

/**
 * @Annotation
 */
class Age18 extends Constraint
{
	public $message = 'Vous devez avoir 18 ans.';

}


use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class Age18Validator extends ConstraintValidator
{
	public function validate($dateNaissance, Constraint $constraint)
	{
		if ($dateNaissance > new \DateTime("18 years ago"))
		{
			$this->context->addViolation($constraint->message);
		}
	}
}


use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class Age18ValidatorTest extends \PHPUnit_Framework_TestCase
{
	private $constraint;

	public function setUp()
	{
		$this->constraint = $this->getMock('Symfony\Component\Validator\Constraint');
	}

	public function testValidate()
	{
		/*ConstraintValidator*/
		$validator = new Age18Validator();
		$context = $this
					->getMockBuilder('Symfony\Component\Validator\ExecutionContext')
					->disableOriginalConstructor()
					->getMock('Age18Validator', array('validate'));

		$context->expects($this->once())
				->method('addViolation')
				->with('Vous devez avoir 18 ans.');
		$validator->initialize($context);
		$validator->validate('10/10/2000', $this->constraint);
	}

	public function tearDown()
	{
		$this->constraint = null;
	}
}






Expectation failed for method name is equal to <string:addViolation> when invoked 1 time(s).
Method was expected to be called 1 times, actually called 0 times.
&#13;
&#13;
&#13;

请你能帮我解决这个问题吗?

谢谢!!

1 个答案:

答案 0 :(得分:6)

检查元素的类型:在验证器类中,您使用两个DateTime对象之间的比较器,但在测试中,您将字符串传递给验证器。

这是我的测试类:

namespace Acme\DemoBundle\Tests\Form;

use Acme\DemoBundle\Validator\Constraints\Age18;
use Acme\DemoBundle\Validator\Constraints\Age18Validator;

class Age18ValidatorTest extends \PHPUnit_Framework_TestCase
{
    private $constraint;
    private $context;

    public function setUp()
    {
        $this->constraint = new Age18();
        $this->context = $this->getMockBuilder('Symfony\Component\Validator\ExecutionContext')->disableOriginalConstructor()->getMock();
    }

    public function testValidate()
    {


        /*ConstraintValidator*/
        $validator = new Age18Validator();
        $validator->initialize( $this->context);

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with($this->constraint->message,array());
        $validator->validate(\Datetime::createFromFormat("d/m/Y","10/10/2000"), $this->constraint);
    }

    public function tearDown()
    {
        $this->constraint = null;
    }
}

希望这个帮助