You are here

public function EntityFieldTest::testEntityIdAssignment in Drupal 9

Same name and namespace in other branches
  1. 8 core/tests/Drupal/KernelTests/Core/Entity/EntityFieldTest.php \Drupal\KernelTests\Core\Entity\EntityFieldTest::testEntityIdAssignment()

Tests explicit entity ID assignment.

File

core/tests/Drupal/KernelTests/Core/Entity/EntityFieldTest.php, line 928

Class

EntityFieldTest
Tests the Entity Field API.

Namespace

Drupal\KernelTests\Core\Entity

Code

public function testEntityIdAssignment() {
  $entity_type = 'entity_test';

  /** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
  $storage = $this->container
    ->get('entity_type.manager')
    ->getStorage($entity_type);

  // Check that an ID can be explicitly assigned on creation.

  /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
  $entity = $this
    ->createTestEntity($entity_type);
  $entity_id = 3;
  $entity
    ->set('id', $entity_id);
  $this
    ->assertSame($entity_id, $entity
    ->id());
  $storage
    ->save($entity);
  $entity = $storage
    ->loadUnchanged($entity
    ->id());
  $this
    ->assertInstanceOf(ContentEntityInterface::class, $entity);

  // Check that an explicitly-assigned ID is preserved on update.
  $storage
    ->save($entity);
  $entity = $storage
    ->loadUnchanged($entity
    ->id());
  $this
    ->assertInstanceOf(ContentEntityInterface::class, $entity);

  // Check that an ID cannot be explicitly assigned on update.
  $this
    ->expectException(EntityStorageException::class);
  $entity
    ->set('id', $entity_id + 1);
  $storage
    ->save($entity);
}