You are here

public function FieldItemSerializationTest::testFieldNormalizeDenormalize in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/serialization/tests/src/Kernel/FieldItemSerializationTest.php \Drupal\Tests\serialization\Kernel\FieldItemSerializationTest::testFieldNormalizeDenormalize()
  2. 10 core/modules/serialization/tests/src/Kernel/FieldItemSerializationTest.php \Drupal\Tests\serialization\Kernel\FieldItemSerializationTest::testFieldNormalizeDenormalize()

Tests normalizing and denormalizing an entity with field item normalizer.

File

core/modules/serialization/tests/src/Kernel/FieldItemSerializationTest.php, line 125

Class

FieldItemSerializationTest
Test field level normalization process.

Namespace

Drupal\Tests\serialization\Kernel

Code

public function testFieldNormalizeDenormalize() {
  $normalized = $this->serializer
    ->normalize($this->entity, 'json');
  $expected_field_value = $this->entity->field_test_text[0]
    ->getValue()['value'] . '::silly_suffix';
  $this
    ->assertEquals($expected_field_value, $normalized['field_test_text'][0]['value'], 'Text field item normalized');
  $denormalized = $this->serializer
    ->denormalize($normalized, $this->entityClass, 'json');
  $this
    ->assertEquals($denormalized->field_test_text[0]
    ->getValue(), $this->entity->field_test_text[0]
    ->getValue(), 'Text field item denormalized.');
  $this
    ->assertEquals($denormalized->field_test_text_default[0]
    ->getValue(), $this->entity->field_test_text_default[0]
    ->getValue(), 'Text field item with default denormalized.');

  // Unset the values for text field that has a default value.
  unset($normalized['field_test_text_default']);
  $denormalized_without_all_fields = $this->serializer
    ->denormalize($normalized, $this->entityClass, 'json');

  // Check that denormalized entity is still the same even if not all fields
  // are not provided.
  $this
    ->assertEquals($denormalized_without_all_fields->field_test_text[0]
    ->getValue(), $this->entity->field_test_text[0]
    ->getValue(), 'Text field item denormalized.');

  // Even though field_test_text_default value was unset before
  // denormalization it should still have the default values for the field.
  $this
    ->assertEquals($denormalized_without_all_fields->field_test_text_default[0]
    ->getValue(), $this->entity->field_test_text_default[0]
    ->getValue(), 'Text field item with default denormalized.');
}