测试symfony 2表单

时间:2012-10-31 13:09:12

标签: forms unit-testing testing symfony symfony-forms

我开发了新类型,但我不知道如何测试它。 断言注释不是加载,也不会调用验证。 有人可以帮帮我吗?

class BarcodeType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->
            add('price');
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Bundles\MyBundle\Form\Model\Barcode',
            'intention'  => 'enable_barcode',
        ));
    }

    public function getName()
    {
        return 'enable_barcode';
    }
}

A有以下用于存储表单数据的模型。

namepspace Bundles\MyBundle\Form\Model;
class Barcode
{
    /**
     * @Assert\Range(
     *      min = "100",
     *      max = "100000",
     *      minMessage = "...",
     *      maxMessage = "..."
     * )
     */
    public $price;
}

我开发了这样的测试,表单没有获得有效数据,但它是有效的! (因为未应用注释) 我尝试添加ValidatorExtension但我不知道如何设置构造函数参数

    function test...()
    {
        $field = $this->factory->createNamed('name', 'barcode');
        $field->bind(
                array(
                    'price'         => 'hello',
        ));

        $data = $field->getData(); 

        $this->assertTrue($field->isValid()); // Must not be valid 

    }

3 个答案:

答案 0 :(得分:1)

不确定为什么需要对表单进行单元测试。您是否对您的实体进行单元测试验证并使用您的预期输出覆盖控制器? 在测试实体验证时您可以使用以下内容:

public function testIncorrectValuesOfUsernameWhileCallingValidation()
{
  $v =  \Symfony\Component\Validator\ValidatorFactory::buildDefault();
  $validator = $v->getValidator();

  $not_valid = array(
    'as', '1234567890_234567890_234567890_234567890_dadadwadwad231',
    "tab\t", "newline\n",
    "Iñtërnâtiônàlizætiøn hasn't happened to ", 'trśżź',
    'semicolon;', 'quote"', 'tick\'', 'backtick`', 'percent%', 'plus+', 'space ', 'mich @l'
  );    

  foreach ($not_valid as $key) {
    $violations = $validator->validatePropertyValue("\Brillante\SampleBundle\Entity\User", "username", $key);
    $this->assertGreaterThan(0, count($violations) ,"dissalow username to be ($key)");
  }

}

答案 1 :(得分:1)

功能测试。假设您使用app / console doctrine生成CRUD:generate:crud with routing = / ss / barcode,并且假设maxMessage =“Too high”,您可以:

class BarcodeControllerTest extends WebTestCase
{
    public function testValidator()
    {
        $client = static::createClient();
        $crawler = $client->request('GET', '/ss/barcode/new');
        $this->assertTrue(200 === $client->getResponse()->getStatusCode());
        // Fill in the form and submit it
        $form = $crawler->selectButton('Create')->form(array(
            'ss_bundle_eavbundle_barcodetype[price]'  => '12',
        ));

        $client->submit($form);
        $crawler = $client->followRedirect();
        // Check data in the show view
        $this->assertTrue($crawler->filter('td:contains("12")')->count() > 0);

        // Edit the entity
        $crawler = $client->click($crawler->selectLink('Edit')->link());
        /* force validator response: */ 
        $form = $crawler->selectButton('Edit')->form(array(
            'ss_bundle_eavbundle_barcodetype[price]'  => '1002',
        ));

        $crawler = $client->submit($form);
        // Check the element contains the maxMessage:
        $this->assertTrue($crawler->filter('ul li:contains("Too high")')->count() > 0);

    }
}

答案 2 :(得分:-1)

包含此行必须在模型中,并在包含类似于您的模型之后尝试。

/* Include the required validators */
use Symfony\Component\Validator\Constraints as Assert;

namespace Bundles\MyBundle\Form\Model;
class Barcode
{
    /**
     * @Assert\Range(
     *      min = "100",
     *      max = "100000",
     *      minMessage = "min message here",
     *      maxMessage = "max message here"
     * )
     */
    public $price;
}
相关问题