function DenormalizeTest::testTypeHandling

Same name and namespace in other branches
  1. 8.9.x core/modules/hal/tests/src/Kernel/DenormalizeTest.php \Drupal\Tests\hal\Kernel\DenormalizeTest::testTypeHandling()

Tests that the type link relation in incoming data is handled correctly.

File

core/modules/hal/tests/src/Kernel/DenormalizeTest.php, line 21

Class

DenormalizeTest
Tests HAL denormalization edge cases for EntityResource.

Namespace

Drupal\Tests\hal\Kernel

Code

public function testTypeHandling() {
  // Valid type.
  $data_with_valid_type = [
    '_links' => [
      'type' => [
        'href' => Url::fromUri('base:rest/type/entity_test/entity_test', [
          'absolute' => TRUE,
        ])->toString(),
      ],
    ],
  ];
  $denormalized = $this->serializer
    ->denormalize($data_with_valid_type, $this->entityClass, $this->format);
  $this->assertEquals($this->entityClass, get_class($denormalized), 'Request with valid type results in creation of correct bundle.');
  // Multiple types.
  $data_with_multiple_types = [
    '_links' => [
      'type' => [
        [
          'href' => Url::fromUri('base:rest/types/foo', [
            'absolute' => TRUE,
          ])->toString(),
        ],
        [
          'href' => Url::fromUri('base:rest/type/entity_test/entity_test', [
            'absolute' => TRUE,
          ])->toString(),
        ],
      ],
    ],
  ];
  $denormalized = $this->serializer
    ->denormalize($data_with_multiple_types, $this->entityClass, $this->format);
  $this->assertEquals($this->entityClass, get_class($denormalized), 'Request with multiple types results in creation of correct bundle.');
  // Invalid type.
  $data_with_invalid_type = [
    '_links' => [
      'type' => [
        'href' => Url::fromUri('base:rest/types/foo', [
          'absolute' => TRUE,
        ])->toString(),
      ],
    ],
  ];
  try {
    $this->serializer
      ->denormalize($data_with_invalid_type, $this->entityClass, $this->format);
    $this->fail('Exception should be thrown when type is invalid.');
  } catch (UnexpectedValueException $e) {
    // Expected exception; just continue testing.
  }
  // No type.
  $data_with_no_type = [
    '_links' => [],
  ];
  try {
    $this->serializer
      ->denormalize($data_with_no_type, $this->entityClass, $this->format);
    $this->fail('Exception should be thrown when no type is provided.');
  } catch (UnexpectedValueException $e) {
    // Expected exception; just continue testing.
  }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.