You are here

class EntityFieldExportTest in REST Views 8

Same name and namespace in other branches
  1. 2.0.x tests/src/Unit/EntityFieldExportTest.php \Drupal\Tests\rest_views\Unit\EntityFieldExportTest

Test the EntityFieldExport views field plugin.

@group rest_views

Hierarchy

Expanded class hierarchy of EntityFieldExportTest

File

tests/src/Unit/EntityFieldExportTest.php, line 31

Namespace

Drupal\Tests\rest_views\Unit
View source
class EntityFieldExportTest extends UnitTestCase {

  /**
   * The EntityFieldExport plugin.
   *
   * @var \Drupal\rest_views\Plugin\views\field\EntityFieldExport|\PHPUnit_Framework_MockObject_MockObject
   */
  private $handler;

  /**
   * The mocked serializer service.
   *
   * @var \Symfony\Component\Serializer\SerializerInterface
   */
  private $serializer;

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();

    // Create our field handler, mocking the required services.
    $entityManager = $this
      ->getMock(EntityManagerInterface::class);
    $formatterPluginManager = $this
      ->getMockBuilder(FormatterPluginManager::class)
      ->disableOriginalConstructor()
      ->getMock();
    $fieldTypePluginManager = $this
      ->getMock(FieldTypePluginManagerInterface::class);
    $languageManager = $this
      ->getMock(LanguageManagerInterface::class);

    /** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = $this
      ->getMock(RendererInterface::class);

    // For the t() function to work, mock the translation service.
    $container = new ContainerBuilder();
    $translation = $this
      ->getMock(TranslationInterface::class);
    $translation
      ->method('translateString')
      ->willReturnCallback(static function (TranslatableMarkup $string) {
      return $string
        ->getUntranslatedString();
    });
    $container
      ->set('string_translation', $translation);
    $container
      ->set('entity.repository', $entityManager);
    $container
      ->set('entity_field.manager', $entityManager);
    Drupal::setContainer($container);
    $this->handler = $this
      ->getMockBuilder(EntityFieldExport::class)
      ->setConstructorArgs([
      [],
      NULL,
      [
        'entity_type' => 'node',
        'field_name' => 'title',
      ],
      $entityManager,
      $formatterPluginManager,
      $fieldTypePluginManager,
      $languageManager,
      $renderer,
    ])
      ->setMethods([
      'getFieldDefinition',
    ])
      ->getMock();

    // Mock the field definition.
    $fieldDefinition = $this
      ->getMock(BaseFieldDefinition::class);
    $fieldDefinition
      ->method('getFieldStorageDefinition')
      ->willReturn($fieldDefinition);
    $fieldDefinition
      ->method('getColumns')
      ->willReturn([]);

    // The handler accesses it through itself, and through the entity manager.
    $this->handler
      ->method('getFieldDefinition')
      ->willReturn($fieldDefinition);
    $entityManager
      ->method('getFieldStorageDefinitions')
      ->with('node')
      ->willReturn([
      'title' => $fieldDefinition,
    ]);

    // Initialize the handler, using a mocked view and display plugin.

    /** @var \Drupal\views\ViewExecutable $view */
    $view = $this
      ->getMockBuilder(ViewExecutable::class)
      ->disableOriginalConstructor()
      ->getMock();
    $view->display_handler = $this
      ->getMockBuilder(DisplayPluginBase::class)
      ->disableOriginalConstructor()
      ->getMock();
    $this->handler
      ->init($view, $view->display_handler);
    $this->serializer = new Serializer([
      new DataNormalizer(),
      new RenderNormalizer($renderer),
    ], [
      new JsonEncoder(),
    ]);
  }

  /**
   * Check that the field does not use multi-type and separator options.
   */
  public function testSettings() {
    $options = $this->handler
      ->defineOptions();
    $this
      ->assertArrayNotHasKey('multi_type', $options);
    $this
      ->assertArrayNotHasKey('separator', $options);
    $form = [];
    $this->handler
      ->multiple_options_form($form, new FormState());
    $this
      ->assertArrayNotHasKey('multi_type', $form);
    $this
      ->assertArrayNotHasKey('separator', $form);
  }

  /**
   * Check that the handler correctly preserves serializable items.
   *
   * @param array $items
   *   Item data to be rendered.
   * @param array $expected
   *   Expected output.
   *
   * @dataProvider providerItems
   *
   * @throws \Exception
   */
  public function testRenderItems(array $items, array $expected) {
    $this->handler->multiple = FALSE;
    $result = $this->handler
      ->renderItems($items);
    $json = $this->serializer
      ->serialize($result, 'json');
    $expected_json = $this->serializer
      ->serialize($expected[0], 'json');
    $this
      ->assertEquals($expected_json, $json);
    $this->handler->multiple = TRUE;
    $result = $this->handler
      ->renderItems($items);
    $json = $this->serializer
      ->serialize($result, 'json');
    $expected_json = $this->serializer
      ->serialize($expected, 'json');
    $this
      ->assertEquals($expected_json, $json);
  }

  /**
   * Data provider for ::testRenderItems().
   *
   * @return array
   *   Test case data.
   */
  public function providerItems() {
    $data[] = [
      'items' => [
        'Lorem',
        'ipsum',
        'dolor',
        'sit',
        'amet',
      ],
      'expected' => [
        'Lorem',
        'ipsum',
        'dolor',
        'sit',
        'amet',
      ],
    ];
    $data[] = [
      'items' => [
        new SerializedData([
          'lorem' => 'ipsum',
        ]),
        new SerializedData([
          'dolor' => TRUE,
        ]),
        new SerializedData([
          'amet' => 42,
        ]),
      ],
      'expected' => [
        [
          'lorem' => 'ipsum',
        ],
        [
          'dolor' => TRUE,
        ],
        [
          'amet' => 42,
        ],
      ],
    ];
    return $data;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
EntityFieldExportTest::$handler private property The EntityFieldExport plugin.
EntityFieldExportTest::$serializer private property The mocked serializer service.
EntityFieldExportTest::providerItems public function Data provider for ::testRenderItems().
EntityFieldExportTest::setUp protected function Overrides UnitTestCase::setUp
EntityFieldExportTest::testRenderItems public function Check that the handler correctly preserves serializable items.
EntityFieldExportTest::testSettings public function Check that the field does not use multi-type and separator options.
PhpunitCompatibilityTrait::getMock Deprecated public function Returns a mock object for the specified class using the available method.
PhpunitCompatibilityTrait::setExpectedException Deprecated public function Compatibility layer for PHPUnit 6 to support PHPUnit 4 code.
UnitTestCase::$randomGenerator protected property The random generator.
UnitTestCase::$root protected property The app root. 1
UnitTestCase::assertArrayEquals protected function Asserts if two arrays are equal by sorting them first.
UnitTestCase::getBlockMockWithMachineName Deprecated protected function Mocks a block with a block plugin. 1
UnitTestCase::getClassResolverStub protected function Returns a stub class resolver.
UnitTestCase::getConfigFactoryStub public function Returns a stub config factory that behaves according to the passed array.
UnitTestCase::getConfigStorageStub public function Returns a stub config storage that returns the supplied configuration.
UnitTestCase::getContainerWithCacheTagsInvalidator protected function Sets up a container with a cache tags invalidator.
UnitTestCase::getRandomGenerator protected function Gets the random generator for the utility methods.
UnitTestCase::getStringTranslationStub public function Returns a stub translation manager that just returns the passed string.
UnitTestCase::randomMachineName public function Generates a unique random string containing letters and numbers.