function FieldEntityTest::testGetEntityNullEntityOptionalRelationship

Same name in other branches
  1. 11.x core/modules/views/tests/src/Functional/Entity/FieldEntityTest.php \Drupal\Tests\views\Functional\Entity\FieldEntityTest::testGetEntityNullEntityOptionalRelationship()
  2. 11.x core/modules/views/tests/src/Kernel/Entity/FieldEntityTest.php \Drupal\Tests\views\Kernel\Entity\FieldEntityTest::testGetEntityNullEntityOptionalRelationship()

Tests the getEntity method returning NULL for an optional relationship.

File

core/modules/views/tests/src/Functional/Entity/FieldEntityTest.php, line 131

Class

FieldEntityTest
Tests the field plugin base integration with the entity system.

Namespace

Drupal\Tests\views\Functional\Entity

Code

public function testGetEntityNullEntityOptionalRelationship() : void {
    $nodeReference = Node::create([
        'type' => 'page',
        'title' => $this->randomString(),
        'status' => NodeInterface::PUBLISHED,
    ]);
    $nodeReference->save();
    $node = Node::create([
        'type' => 'page',
        'title' => $this->randomString(),
        'status' => NodeInterface::PUBLISHED,
        'field_test_reference' => [
            'target_id' => $nodeReference->id(),
        ],
    ]);
    $node->save();
    $this->drupalLogin($this->drupalCreateUser([
        'access content',
    ]));
    $view = Views::getView('test_field_get_entity_null');
    $this->executeView($view);
    // Second row will be $node.
    $row = $view->result[1];
    $entity = $view->field['nid']
        ->getEntity($row);
    $this->assertEquals($nodeReference->id(), $entity->id());
    // Tests optional relationships with NULL entities don't log an error.
    $nodeReference->delete();
    // Use a mock logger so we can check that no errors were logged.
    $loggerFactory = $this->createMock(LoggerChannelFactoryInterface::class);
    $loggerFactory->expects($this->never())
        ->method('get');
    $container = \Drupal::getContainer();
    $container->set('logger.factory', $loggerFactory);
    \Drupal::setContainer($container);
    $view = Views::getView('test_field_get_entity_null');
    $this->executeView($view);
    // First row will be $node since the other is now deleted.
    $row = $view->result[0];
    $this->assertNull($view->field['nid']
        ->getEntity($row));
}

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