EntityHasFieldConstraintValidatorTest.php in Drupal 10
File
core/tests/Drupal/KernelTests/Core/Entity/EntityHasFieldConstraintValidatorTest.php
View source
<?php
namespace Drupal\KernelTests\Core\Entity;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
class EntityHasFieldConstraintValidatorTest extends EntityKernelTestBase {
protected static $modules = [
'entity_test_constraints',
];
protected function setUp() : void {
parent::setUp();
$this
->installEntitySchema('entity_test_constraints');
$this
->createUser();
}
public function testValidation() {
$this->state
->set('entity_test_constraints.build', [
'EntityHasField' => 'body',
]);
$entity_type_manager = $this->container
->get('entity_type.manager');
$entity_type_manager
->clearCachedDefinitions();
$this->container
->get('typed_data_manager')
->clearCachedDefinitions();
$storage = $entity_type_manager
->getStorage('entity_test_constraints');
$entity = $storage
->create();
$violations = $entity
->validate();
$this
->assertCount(1, $violations);
$this
->assertEquals('The entity must have the <em class="placeholder">body</em> field.', $violations[0]
->getMessage());
$storage
->save($entity);
$field_storage = FieldStorageConfig::create([
'type' => 'string',
'entity_type' => $entity
->getEntityTypeId(),
'field_name' => 'body',
]);
$field_storage
->save();
FieldConfig::create([
'field_storage' => $field_storage,
'bundle' => $entity
->bundle(),
])
->save();
$this
->assertCount(0, $storage
->loadUnchanged(1)
->validate());
}
}