You are here

public function FieldValidationTest::testCardinalityConstraint in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/field/tests/src/Kernel/FieldValidationTest.php \Drupal\Tests\field\Kernel\FieldValidationTest::testCardinalityConstraint()

Tests that the number of values is validated against the field cardinality.

File

core/modules/field/tests/src/Kernel/FieldValidationTest.php, line 45

Class

FieldValidationTest
Tests field validation.

Namespace

Drupal\Tests\field\Kernel

Code

public function testCardinalityConstraint() {
  $cardinality = $this->fieldTestData->field_storage
    ->getCardinality();
  $entity = $this->entity;
  for ($delta = 0; $delta < $cardinality + 1; $delta++) {
    $entity->{$this->fieldTestData->field_name}[] = [
      'value' => 1,
    ];
  }

  // Validate the field.
  $violations = $entity->{$this->fieldTestData->field_name}
    ->validate();

  // Check that the expected constraint violations are reported.
  $this
    ->assertCount(1, $violations);
  $this
    ->assertEquals('', $violations[0]
    ->getPropertyPath());
  $this
    ->assertEquals(t('%name: this field cannot hold more than @count values.', [
    '%name' => $this->fieldTestData->field
      ->getLabel(),
    '@count' => $cardinality,
  ]), $violations[0]
    ->getMessage());
}