3 namespace Drupal\KernelTests\Core\Entity;
5 use Drupal\Core\Field\BaseFieldDefinition;
8 * Tests validation constraints for ValidReferenceConstraintValidator.
12 class ValidReferenceConstraintValidatorTest extends EntityKernelTestBase {
15 * The typed data manager to use.
17 * @var \Drupal\Core\TypedData\TypedDataManager
24 public static $modules = ['field', 'user'];
29 protected function setUp() {
31 $this->installSchema('user', ['users_data']);
32 $this->typedData = $this->container->get('typed_data_manager');
36 * Tests the ValidReferenceConstraintValidator.
38 public function testValidation() {
39 // Create a test entity to be referenced.
40 $entity = $this->createUser();
41 // By default entity references already have the ValidReference constraint.
42 $definition = BaseFieldDefinition::create('entity_reference')
43 ->setSettings(['target_type' => 'user']);
45 $typed_data = $this->typedData->create($definition, ['target_id' => $entity->id()]);
46 $violations = $typed_data->validate();
47 $this->assertFalse($violations->count(), 'Validation passed for correct value.');
49 // NULL is also considered a valid reference.
50 $typed_data = $this->typedData->create($definition, ['target_id' => NULL]);
51 $violations = $typed_data->validate();
52 $this->assertFalse($violations->count(), 'Validation passed for correct value.');
54 $typed_data = $this->typedData->create($definition, ['target_id' => $entity->id()]);
55 // Delete the referenced entity.
57 $violations = $typed_data->validate();
58 $this->assertTrue($violations->count(), 'Validation failed for incorrect value.');
60 // Make sure the information provided by a violation is correct.
61 $violation = $violations[0];
62 $this->assertEqual($violation->getMessage(), t('The referenced entity (%type: %id) does not exist.', [
64 '%id' => $entity->id(),
65 ]), 'The message for invalid value is correct.');
66 $this->assertEqual($violation->getRoot(), $typed_data, 'Violation root is correct.');