function EntityReferenceFieldTest::testTargetEntityNoLoad
Same name in other branches
- 9 core/tests/Drupal/KernelTests/Core/Entity/EntityReferenceFieldTest.php \Drupal\KernelTests\Core\Entity\EntityReferenceFieldTest::testTargetEntityNoLoad()
- 10 core/tests/Drupal/KernelTests/Core/Entity/EntityReferenceFieldTest.php \Drupal\KernelTests\Core\Entity\EntityReferenceFieldTest::testTargetEntityNoLoad()
- 11.x core/tests/Drupal/KernelTests/Core/Entity/EntityReferenceFieldTest.php \Drupal\KernelTests\Core\Entity\EntityReferenceFieldTest::testTargetEntityNoLoad()
Tests that the target entity is not unnecessarily loaded.
File
-
core/
tests/ Drupal/ KernelTests/ Core/ Entity/ EntityReferenceFieldTest.php, line 376
Class
- EntityReferenceFieldTest
- Tests for the entity reference field.
Namespace
Drupal\KernelTests\Core\EntityCode
public function testTargetEntityNoLoad() {
// Setup a test entity type with an entity reference field to itself. We use
// a special storage class throwing exceptions when a load operation is
// triggered to be able to detect them.
$entity_type = clone $this->entityTypeManager
->getDefinition('entity_test_update');
$entity_type->setHandlerClass('storage', '\\Drupal\\entity_test\\EntityTestNoLoadStorage');
$this->state
->set('entity_test_update.entity_type', $entity_type);
$definitions = [
'target_reference' => BaseFieldDefinition::create('entity_reference')->setSetting('target_type', $entity_type->id())
->setSetting('handler', 'default'),
];
$this->state
->set('entity_test_update.additional_base_field_definitions', $definitions);
$this->entityTypeManager
->clearCachedDefinitions();
$this->installEntitySchema($entity_type->id());
// Create the target entity.
$storage = $this->entityTypeManager
->getStorage($entity_type->id());
$target_id = $this->generateRandomEntityId();
$target = $storage->create([
'id' => $target_id,
'name' => $this->randomString(),
]);
$target->save();
$this->assertEqual($target_id, $target->id(), 'The target entity has a random identifier.');
// Check that populating the reference with an existing target id does not
// trigger a load operation.
$message = 'The target entity was not loaded.';
try {
$entity = $this->entityTypeManager
->getStorage($entity_type->id())
->create([
'name' => $this->randomString(),
]);
$entity->target_reference = $target_id;
} catch (EntityStorageException $e) {
$this->fail($message);
}
// Check that the storage actually triggers the expected exception when
// trying to load the target entity.
$message = 'An exception is thrown when trying to load the target entity';
try {
$storage->load($target_id);
$this->fail($message);
} catch (EntityStorageException $e) {
// Expected exception; just continue testing.
}
}
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.