Symfony NotBlank constraint allow blank string

I’m working with Symfony5 and ApiPlatform with phpunit for the tests

I’m running tests on field validation.

My issue comes from the fact that I want to restrain the user’s possiblity to enter a blank string in a property named name as follow :

/**
 * @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"}
 *          }
 *     }
 * )
 * @ORMEntity(repositoryClass=ConsultationTypeRepository::class)
 */
class ClassName
{
    /**
     * @ORMId
     * @ORMGeneratedValue
     * @ORMColumn(type="integer")
     * @Groups({"cons:read", "cons:list", "some:read", "thing:read"})
     */
    private $id;

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

Here is my test :

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

Now I receive a 201 instead of the expected 400.

While other tests concerning the regex or the length of the string return 400 as expected.

I don’t understand why the NotBlank() seem to not trigger on this test.

Any idea ?

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *