3

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

这是我的不同类和运行 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.

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

谢谢!!

4

1 回答 1

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;
    }
}

希望这有帮助

于 2014-10-25T13:42:05.783 回答