3 namespace Drupal\KernelTests\Core\Entity;
5 use Drupal\field\Entity\FieldConfig;
6 use Drupal\field\Entity\FieldStorageConfig;
9 * @covers \Drupal\Core\Entity\Plugin\Validation\Constraint\EntityHasFieldConstraintValidator
13 class EntityHasFieldConstraintValidatorTest extends EntityKernelTestBase {
18 public static $modules = ['entity_test_constraints'];
23 protected function setUp() {
25 $this->installEntitySchema('entity_test_constraints');
29 public function testValidation() {
30 $this->state->set('entity_test_constraints.build', [
31 'EntityHasField' => 'body',
34 /** @var \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager */
35 $entity_type_manager = $this->container->get('entity_type.manager');
36 $entity_type_manager->clearCachedDefinitions();
38 // Clear the typed data cache so that the entity has the correct constraints
40 $this->container->get('typed_data_manager')->clearCachedDefinitions();
42 $storage = $entity_type_manager->getStorage('entity_test_constraints');
44 /** @var \Drupal\entity_test\Entity\EntityTestConstraints $entity */
45 $entity = $storage->create();
46 // We should get a violation if we try to validate the entity before the
47 // field has been created.
48 $violations = $entity->validate();
49 $this->assertCount(1, $violations);
50 $this->assertEquals($violations[0]->getMessage(), 'The entity must have the <em class="placeholder">body</em> field.');
51 $storage->save($entity);
54 $field_storage = FieldStorageConfig::create([
56 'entity_type' => $entity->getEntityTypeId(),
57 'field_name' => 'body',
59 $field_storage->save();
62 'field_storage' => $field_storage,
63 'bundle' => $entity->bundle(),
66 // Now that the field has been created, there should be no violations.
67 $this->assertCount(0, $storage->loadUnchanged(1)->validate());