Validator validation constraints with symfony2.3
I would like to make a test unit using a constraint, but I have this error when running my test
These are my different classes and getting error after running 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.
Please help me to solve this problem?
Thanks you!
+3
patricko
source
to share
1 answer
Check the element type: in the validator class, you are using a comparator between two DateTime objects, but in the test, you are passing a string to the validator.
This is my test class:
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;
}
}
Hope for this help
+6
Matteo
source
to share