微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Symfony NotBlank约束允许空白字符串

如何解决Symfony NotBlank约束允许空白字符串

我正在与Symfony5一起使用ApiPlatformPHPunit进行测试

我正在对现场验证进行测试。

我的问题来自以下事实:我想限制用户在名为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","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()似乎没有在此测试中触发。

有什么主意吗?

解决方法

我认为这是因为您已经使用驼峰大小写而不是蛇形大小写声明了post操作属性。骆驼的情况下只能在ApiResource注释的顶层使用。

当前,您仅声明了操作的method。这里没用。

  • normalizationContext => normalization_context
  • validationGroups => validation_groups

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。