【问题标题】:Symfony NotBlank constraint allow blank stringSymfony NotBlank 约束允许空白字符串
【发布时间】:2021-02-24 11:35:11
【问题描述】:

我正在使用 Symfony5ApiPlatformphpunit 进行测试

我正在对字段验证进行测试。

我的问题来自于我想限制用户在名为name 的属性中输入空白字符串的可能性,如下所示:

/**
 * @ApiResource(
 *     attributes={
 *          "normalization_context"={"groups"={"cons:read", "cons:list"}},
 *          "denormalization_context"={"groups"={"cons:write"}}
 *     },
 *     collectionOperations={
 *          "get"={
 *              "mehtod"="GET",
 *              "normalization_context"={"groups"={"cons:list"}},
 *          },
 *          "post"={
 *              "method"="POST"
 *              "normalizationContext"={"groups"={"cons:write"}},
 *              "validationGroups"={"create"}
 *          }
 *     }
 * )
 * @ORM\Entity(repositoryClass=ConsultationTypeRepository::class)
 */
class ClassName
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     * @Groups({"cons:read", "cons:list", "some:read", "thing:read"})
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255, nullable=false)
     * @Groups({"cons:read", "cons:write", "cons:list", "some:read", "thing:read", "availability:read"})
     * @Assert\NotBlank (
     *     groups={"create"},
     *     message="Le nom ne peut pas être vide."
     * )
     * @Assert\Length(
     *     max = 255,
     *     maxMessage = "Le nom ne peut pas excéder 255 charactères",
     *     allowEmptyString = false
     * )
     * @Assert\Regex(
     *     pattern="/\d/",
     *     match=false,
     *     message="Le nom ne peut pas contenir de nombre"
     * )
     */
    private $name;

这是我的测试:

public function testRoleAdminCanNotPostConsultationWithBlankName(): void
    {
        $body = '{ "name": ""}';
        $res = $this->buildPostPutRequest(
            Actions::POST,
            self::TYPE_CONSULTATION_ROUTE,
            $body,
            self::ADMIN_CREDENTIALS
        );
        $this->assertResponseStatusCodeSame(400);
    }

现在我收到了201,而不是预期的400

而其他有关正则表达式或字符串长度的测试按预期返回 400

我不明白为什么 NotBlank() 似乎没有在此测试中触发。

有什么想法吗?

【问题讨论】:

    标签: docker symfony validation assert api-platform.com


    【解决方案1】:

    我认为这是因为您已使用驼峰式而不是蛇式来声明您的 post 操作属性。驼峰式大小写只能在 ApiResource 注释的顶层使用。

    目前,您只声明了您的操作的method。这在这里没用。

    • normalizationContext => normalization_context
    • validationGroups => 验证组

    您还声明了mehtod 属性,而不是在GET 操作中的method

    【讨论】:

    • 感谢您的评论。它确实帮助我解决了我的问题!
    猜你喜欢
    • 1970-01-01
    • 2015-12-17
    • 2014-07-18
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    • 1970-01-01
    相关资源
    最近更新 更多