function LinkFormatterTest::testFormatterLinkItem

Same name in other branches
  1. 9 core/modules/link/tests/src/Unit/LinkFormatterTest.php \Drupal\Tests\link\Unit\LinkFormatterTest::testFormatterLinkItem()
  2. 10 core/modules/link/tests/src/Unit/LinkFormatterTest.php \Drupal\Tests\link\Unit\LinkFormatterTest::testFormatterLinkItem()

Tests when LinkItem::getUrl returns a functional URL.

File

core/modules/link/tests/src/Unit/LinkFormatterTest.php, line 110

Class

LinkFormatterTest
Tests the Field Formatter for the link field type.

Namespace

Drupal\Tests\link\Unit

Code

public function testFormatterLinkItem() : void {
    $expectedUrl = Url::fromUri('route:<front>');
    $linkItem = $this->createMock(LinkItemInterface::class);
    $entity = $this->createMock(EntityInterface::class);
    $linkItem->expects($this->any())
        ->method('getParent')
        ->willReturn($entity);
    $linkItem->expects($this->once())
        ->method('getUrl')
        ->willReturn($expectedUrl);
    $linkItem->expects($this->any())
        ->method('__get')
        ->with('options')
        ->willReturn([]);
    $fieldDefinition = $this->createMock(FieldDefinitionInterface::class);
    $fieldList = new FieldItemList($fieldDefinition, '', $linkItem);
    $fieldTypePluginManager = $this->createMock(FieldTypePluginManagerInterface::class);
    $fieldTypePluginManager->expects($this->once())
        ->method('createFieldItem')
        ->willReturn($linkItem);
    $urlGenerator = $this->createMock(UrlGenerator::class);
    $urlGenerator->expects($this->once())
        ->method('generateFromRoute')
        ->with('<front>', [], [], FALSE)
        ->willReturn('http://example.com');
    $container = new ContainerBuilder();
    $container->set('plugin.manager.field.field_type', $fieldTypePluginManager);
    $container->set('url_generator', $urlGenerator);
    \Drupal::setContainer($container);
    $fieldList->setValue([
        $linkItem,
    ]);
    $pathValidator = $this->createMock(PathValidatorInterface::class);
    $linkFormatter = new LinkFormatter('', [], $fieldDefinition, [], '', '', [], $pathValidator);
    $elements = $linkFormatter->viewElements($fieldList, 'zh');
    $this->assertEquals([
        [
            '#type' => 'link',
            '#title' => 'http://example.com',
            '#url' => $expectedUrl,
        ],
    ], $elements);
}

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