You are here

public function ContentEntityBaseUnitTest::testGetFields in Drupal 9

Same name and namespace in other branches
  1. 8 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 531

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) {

  // Mock ContentEntityBase.
  $mock_base = $this
    ->getMockBuilder('Drupal\\Core\\Entity\\ContentEntityBase')
    ->disableOriginalConstructor()
    ->setMethods([
    'getFieldDefinitions',
    'get',
  ])
    ->getMockForAbstractClass();

  // Mock field definition objects for each element of $field_definitions.
  $mocked_field_definitions = [];
  foreach ($field_definitions as $name) {
    $mock_definition = $this
      ->getMockBuilder('Drupal\\Core\\Field\\FieldDefinitionInterface')
      ->setMethods([
      'isComputed',
    ])
      ->getMockForAbstractClass();

    // 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));
}