function ContentEntityBaseUnitTest::testGetFields

Same name in other branches
  1. 9 core/tests/Drupal/Tests/Core/Entity/ContentEntityBaseUnitTest.php \Drupal\Tests\Core\Entity\ContentEntityBaseUnitTest::testGetFields()
  2. 8.9.x core/tests/Drupal/Tests/Core/Entity/ContentEntityBaseUnitTest.php \Drupal\Tests\Core\Entity\ContentEntityBaseUnitTest::testGetFields()
  3. 11.x core/tests/Drupal/Tests/Core/Entity/ContentEntityBaseUnitTest.php \Drupal\Tests\Core\Entity\ContentEntityBaseUnitTest::testGetFields()

@covers ::getFields @dataProvider providerGetFields

File

core/tests/Drupal/Tests/Core/Entity/ContentEntityBaseUnitTest.php, line 613

Class

ContentEntityBaseUnitTest
@coversDefaultClass \Drupal\Core\Entity\ContentEntityBase @group Entity @group Access

Namespace

Drupal\Tests\Core\Entity

Code

public function testGetFields($expected, $include_computed, $is_computed, $field_definitions) : void {
    // Mock ContentEntityBase.
    $mock_base = $this->getMockBuilder(ContentEntityBaseMockableClass::class)
        ->disableOriginalConstructor()
        ->onlyMethods([
        'getFieldDefinitions',
        'get',
    ])
        ->getMock();
    // Mock field definition objects for each element of $field_definitions.
    $mocked_field_definitions = [];
    foreach ($field_definitions as $name) {
        $mock_definition = $this->createMock('Drupal\\Core\\Field\\FieldDefinitionInterface');
        // Set expectations for isComputed(). isComputed() gets called whenever
        // $include_computed is FALSE, but not otherwise. It returns the value of
        // $is_computed.
        $mock_definition->expects($this->exactly($include_computed ? 0 : 1))
            ->method('isComputed')
            ->willReturn($is_computed);
        $mocked_field_definitions[$name] = $mock_definition;
    }
    // Set up expectations for getFieldDefinitions().
    $mock_base->expects($this->once())
        ->method('getFieldDefinitions')
        ->willReturn($mocked_field_definitions);
    // How many time will we call get()? Since we are rigging all defined fields
    // to be computed based on $is_computed, then if $include_computed is FALSE,
    // get() will never be called.
    $get_count = 0;
    if ($include_computed) {
        $get_count = count($field_definitions);
    }
    // Set up expectations for get(). It simply returns the name passed in.
    $mock_base->expects($this->exactly($get_count))
        ->method('get')
        ->willReturnArgument(0);
    // Exercise getFields().
    $this->assertEquals($expected, $mock_base->getFields($include_computed));
}

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