function UniqueFieldConstraintTest::testViolationDespiteNoAccess

Same name in other branches
  1. 10 core/tests/Drupal/KernelTests/Core/Validation/UniqueFieldConstraintTest.php \Drupal\KernelTests\Core\Validation\UniqueFieldConstraintTest::testViolationDespiteNoAccess()

Tests validating inaccessible entities.

The unique_field_constraint_test_entity_test_access() function forbids 'view' access to entity_test entities.

@covers ::validate

File

core/tests/Drupal/KernelTests/Core/Validation/UniqueFieldConstraintTest.php, line 127

Class

UniqueFieldConstraintTest
Tests the unique field value validation constraint.

Namespace

Drupal\KernelTests\Core\Validation

Code

public function testViolationDespiteNoAccess() : void {
    $this->installEntitySchema('entity_test');
    // Create and save an entity with a given field value in the field that has
    // the unique constraint.
    EntityTest::create([
        'name' => 'A totally unique entity name',
    ])->save();
    // Prepare a second entity with the same value in the unique field.
    $entity = EntityTest::create([
        'name' => 'A totally unique entity name',
    ]);
    
    /** @var \Symfony\Component\Validator\ConstraintViolationList $violations */
    $violations = $entity->get('name')
        ->validate();
    $message = new FormattableMarkup('A @entity_type with @field_name %value already exists.', [
        '%value' => 'A totally unique entity name',
        '@entity_type' => $entity->getEntityType()
            ->getSingularLabel(),
        '@field_name' => 'Name',
    ]);
    // Check that the validation has created the appropriate violation.
    $this->assertCount(1, $violations);
    $this->assertEquals($message, $violations[0]->getMessage());
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.