function EntityTypeConstraintValidatorTest::testValidation

Same name and namespace in other branches
  1. 9 core/tests/Drupal/KernelTests/Core/Entity/EntityTypeConstraintValidatorTest.php \Drupal\KernelTests\Core\Entity\EntityTypeConstraintValidatorTest::testValidation()
  2. 8.9.x core/tests/Drupal/KernelTests/Core/Entity/EntityTypeConstraintValidatorTest.php \Drupal\KernelTests\Core\Entity\EntityTypeConstraintValidatorTest::testValidation()
  3. 10 core/tests/Drupal/KernelTests/Core/Entity/EntityTypeConstraintValidatorTest.php \Drupal\KernelTests\Core\Entity\EntityTypeConstraintValidatorTest::testValidation()

Tests the EntityTypeConstraintValidator.

File

core/tests/Drupal/KernelTests/Core/Entity/EntityTypeConstraintValidatorTest.php, line 36

Class

EntityTypeConstraintValidatorTest
Tests validation constraints for EntityTypeConstraintValidator.

Namespace

Drupal\KernelTests\Core\Entity

Code

public function testValidation() : void {
    // Create a typed data definition with an EntityType constraint.
    $entity_type = 'node';
    $definition = DataDefinition::create('entity_reference')->setConstraints([
        'EntityType' => $entity_type,
    ]);
    // Test the validation.
    $node = $this->container
        ->get('entity_type.manager')
        ->getStorage('node')
        ->create([
        'type' => 'page',
    ]);
    $typed_data = $this->typedData
        ->create($definition, $node);
    $violations = $typed_data->validate();
    $this->assertEquals(0, $violations->count(), 'Validation passed for correct value.');
    // Test the validation when an invalid value (in this case a user entity)
    // is passed.
    $account = $this->createUser();
    $typed_data = $this->typedData
        ->create($definition, $account);
    $violations = $typed_data->validate();
    $this->assertEquals(1, $violations->count(), 'Validation failed for incorrect value.');
    // Make sure the information provided by a violation is correct.
    $violation = $violations[0];
    $this->assertEquals(sprintf('The entity must be of type %s.', $entity_type), $violation->getMessage(), 'The message for invalid value is correct.');
    $this->assertEquals($typed_data, $violation->getRoot(), 'Violation root is correct.');
    $this->assertEquals($account, $violation->getInvalidValue(), 'The invalid value is set correctly in the violation.');
}

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