You are here

public function ReferenceWidgetTest::testGetOptions in Select (or other) 8

Same name and namespace in other branches
  1. 8.3 Tests/src/Unit/ReferenceWidgetTest.php \Drupal\Tests\select_or_other\Unit\ReferenceWidgetTest::testGetOptions()
  2. 4.x tests/src/Unit/ReferenceWidgetTest.php \Drupal\Tests\select_or_other\Unit\ReferenceWidgetTest::testGetOptions()

Test if defaultSettings() returns the correct keys.

File

tests/src/Unit/ReferenceWidgetTest.php, line 79

Class

ReferenceWidgetTest
Tests the form element implementation.

Namespace

Drupal\Tests\select_or_other\Unit

Code

public function testGetOptions() {
  $entity_id = 1;
  $entity_label = 'Label';
  $entity_mock = $this
    ->getMockBuilder('\\Drupal\\Core\\Entity\\EntityBase')
    ->disableOriginalConstructor()
    ->getMock();
  $entity_mock
    ->expects($this
    ->exactly(1))
    ->method('id')
    ->willReturn($entity_id);
  $entity_mock
    ->expects($this
    ->exactly(2))
    ->method('label')
    ->willReturn($entity_label);
  $entity_storage_mock = $this
    ->getMockForAbstractClass('\\Drupal\\Core\\Entity\\EntityStorageInterface');
  $entity_storage_mock
    ->expects($this
    ->exactly(2))
    ->method('loadByProperties')
    ->willReturnOnConsecutiveCalls([], [
    $entity_mock,
  ]);
  $mock = $this->mockBuilder
    ->disableOriginalConstructor()
    ->setMethods([
    'getEntityStorage',
    'getBundleKey',
    'getSelectionHandlerSetting',
  ])
    ->getMock();
  $mock
    ->expects($this
    ->exactly(2))
    ->method('getEntityStorage')
    ->willReturn($entity_storage_mock);
  $mock
    ->expects($this
    ->exactly(2))
    ->method('getBundleKey')
    ->willReturn('bundle');
  $mock
    ->expects($this
    ->exactly(2))
    ->method('getSelectionHandlerSetting')
    ->willReturn('target_bundle');
  $get_options = new ReflectionMethod($mock, 'getOptions');
  $get_options
    ->setAccessible(TRUE);

  // First invocation returns an empty array because there are no entities.
  $options = $get_options
    ->invoke($mock, $this
    ->getMockForAbstractClass('Drupal\\Core\\Entity\\FieldableEntityInterface'));
  $expected = [];
  $this
    ->assertArrayEquals($options, $expected);

  // Second invocation returns a key=>value array because there is one entity.
  $options = $get_options
    ->invoke($mock, $this
    ->getMockForAbstractClass('Drupal\\Core\\Entity\\FieldableEntityInterface'));
  $expected = [
    "{$entity_label} ({$entity_id})" => $entity_label,
  ];
  $this
    ->assertArrayEquals($options, $expected);
}