Aşağıdaki örnek tek bir class alanı için yaratılan assert validation constraint testi için kullanılır.


Validation constraint class


namespace Application\BackendBundle\Validator\Constraint;

use Symfony\Component\Validator\Constraint;

/**
* @Annotation
*/
class Username extends Constraint
{
const INVALID_CONTENT = 'Username must form of only alphabetic and numeric characters.';

public function validatedBy()
{
return get_class($this).'Validator';
}
}

namespace Application\BackendBundle\Validator\Constraint;

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

class UsernameValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
if (! ctype_alnum($value)) {
$this->context
->buildViolation($constraint::INVALID_CONTENT)
->atPath('username')
->addViolation();
}
}
}

PhpSpec


namespace spec\Application\BackendBundle\Validator\Constraint;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Validator\Violation\ConstraintViolationBuilderInterface;
use Application\BackendBundle\Validator\Constraint\Username as Constraint;

class UsernameValidatorSpec extends ObjectBehavior
{
function it_is_initializable()
{
$this->shouldHaveType('Application\BackendBundle\Validator\Constraint\UsernameValidator');
}

function it_should_not_validate_illegal_characters(
ExecutionContextInterface $context,
ConstraintViolationBuilderInterface $builder,
Constraint $constraint
) {
$this->initialize($context);

$builder->addViolation()->shouldBeCalled();
$builder->atPath('username')->willReturn($builder);

$context->buildViolation(
'Username must form of only alphabetic and numeric characters.'
)->willReturn($builder);

$this->validate('ab@£$123', $constraint);
}

function it_should_validate_legal_value(
ExecutionContextInterface $context,
ConstraintViolationBuilderInterface $builder,
Constraint $constraint
) {
$this->initialize($context);

$builder->addViolation()->shouldNotBeCalled();

$this->validate('inanzzz', $constraint);
}
}