Code snippets for symfony 1.x

Navigation

Snippets tagged "validator test"

Test a validator class

If you create a custom validator, you might want to test it by creating a unit test script.

This is a sample unit test script for testing validators.

test/unit/myFooBarValidatorTest.php

<?php
$app='frontend'; // Necessary for fonctional boostrap
include(dirname(__FILE__).'/../test/bootstrap/unit.php');
include(dirname(__FILE__).'/../test/bootstrap/functional.php');
require_once(dirname(__FILE__).'/../../lib/validator/myFooBarValidator.class.php');
 
$context = sfContext::getInstance();
$request = $context->getRequest();
 
$manager = new sfValidatorManager();
$manager->initialize($context);
$validator = new myFooBarValidator();
$validator->initialize($context);
 
// The values to validate.
// You can make a second array with values
// that are supposed to fail and do another
// loop below.
$values = Array('foo', 'bar');
 
$t = new lime_test(count($values) * 2, new lime_output_color());
 
$t->diag('myFooBarValidator()');
 
foreach ( $values as $value ) {
  // Re-initialize the validation entry
  // Without this, the first failure would
  // cause any additional validation to
  // be skipped
  $manager->registerName('myname', false);
  $manager->registerValidator('myname', $validator);
 
  $request->setParameter('myname', $value);
  $retval = $manager->execute();
  $t->is($retval, true);
  $t->is($request->getErrors(), Array());
 
  // We remove the error so that the next loop
  // does not carry the error.
  $request->removeError('myname');
}
by Christian Roy on 2007-06-04, tagged test  validator