function ValidReferenceConstraintValidatorTest::testValidation

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

Tests the ValidReferenceConstraintValidator.

File

core/tests/Drupal/KernelTests/Core/Entity/ValidReferenceConstraintValidatorTest.php, line 57

Class

ValidReferenceConstraintValidatorTest
Tests validation constraints for ValidReferenceConstraintValidator.

Namespace

Drupal\KernelTests\Core\Entity

Code

public function testValidation() : void {
    // Create a test entity to be referenced.
    $entity = $this->createUser();
    // By default entity references already have the ValidReference constraint.
    $definition = BaseFieldDefinition::create('entity_reference')->setSettings([
        'target_type' => 'user',
    ]);
    $typed_data = $this->typedData
        ->create($definition, [
        'target_id' => $entity->id(),
    ]);
    $violations = $typed_data->validate();
    $this->assertEquals(0, $violations->count(), 'Validation passed for correct value.');
    // NULL is also considered a valid reference.
    $typed_data = $this->typedData
        ->create($definition, [
        'target_id' => NULL,
    ]);
    $violations = $typed_data->validate();
    $this->assertEquals(0, $violations->count(), 'Validation passed for correct value.');
    $typed_data = $this->typedData
        ->create($definition, [
        'target_id' => $entity->id(),
    ]);
    // Delete the referenced entity.
    $entity->delete();
    $violations = $typed_data->validate();
    $this->assertGreaterThan(0, $violations->count(), 'Validation failed for incorrect value.');
    // Make sure the information provided by a violation is correct.
    $violation = $violations[0];
    $this->assertEquals(sprintf('The referenced entity (user: %s) does not exist.', $entity->id()), $violation->getMessage(), 'The message for invalid value is correct.');
    $this->assertEquals($typed_data, $violation->getRoot(), 'Violation root is correct.');
}

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