Symfony2:测试实体验证约束 [英] Symfony2: Testing entity validation constraints

查看:32
本文介绍了Symfony2:测试实体验证约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人有在 Symfony2 中对实体的验证约束进行单元测试的好方法?

Does anyone have a good way to unit test an entity's validation constraints in Symfony2?

理想情况下,我希望能够访问单元测试中的依赖注入容器,然后我才能访问验证器服务.一旦我有了验证器服务,我就可以手动运行它:

Ideally I want to have access to the Dependency Injection Container within the unit test which would then give me access to the validator service. Once I have the validator service I can run it manually:

$errors = $validator->validate($entity);

我可以扩展 WebTestCase 然后创建一个 client 以根据文档访问容器,但是感觉不对.文档中的 WebTestCaseclient 更像是一种测试 动作 整体的工具,因此使用它来单元化感觉很糟糕测试一个实体.

I could extend WebTestCase and then create a client to get to the container as per the docs however it doesn't feel right. The WebTestCase and client read in the docs as more of a facility to test actions as a whole and therefore it feels broken to use it to unit test an entity.

那么,有谁知道如何 a) 获取容器或 b) 在单元测试中创建验证器?

So, does anyone know how to either a) get the container or b) create the validator inside a unit test?

推荐答案

好吧,既然这得到了两票,我猜其他人会感兴趣.

Ok since this got two votes I guess other people are interested.

我决定把我的铲子拿出来,惊喜地发现(到目前为止)这并不难.

I decided to get my shovel out and was pleasantly surprised (so far anyway) that this wasn't at all difficult to pull off.

我记得每个 Symfony2 组件都可以在独立模式下使用,因此我可以自己创建验证器.

I remembered that each Symfony2 component can be used in a stand alone mode and therefore that I could create the validator myself.

查看以下文档:https://github.com/symfony/Validator/blob/master/ValidatorFactory.php

我意识到,因为有一个 ValidatorFactory,所以创建一个验证器是微不足道的(特别是对于我是通过注释完成的验证,尽管如果您查看我上面链接的页面上的文档块,您还会找到验证的方法xml 和 yml).

I realised that since there was a ValidatorFactory it was trivial to create a validator (especially for validation done by annotations which I am, although if you look at the docblock on the page I linked above you'll also find ways to validate xml and yml).

首先:

# Symfony >=2.1
use Symfony\Component\Validator\Validation;
# Symfony <2.1
use Symfony\Component\Validator\ValidatorFactory;

然后:

# Symfony >=2.1
$validator = Validation::createValidatorBuilder()->enableAnnotationMapping()->getValidator();
# Symfony <2.1
$validator = ValidatorFactory::buildDefault()->getValidator();

$errors = $validator->validate($entity);

$this->assertEquals(0, count($errors));

我希望这能帮助那些良心不允许他们只使用 WebTestCase 的其他人;)

I hope this helps anyone else whose conscience wouldn't allow them to just use WebTestCase ;).

这篇关于Symfony2:测试实体验证约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆