public function SelectOrOtherWidgetBaseTest::testGetSelectedOptions in Select (or other) 8.3
Tests the functionality of SelectOrOtherWidgetBase::getSelectedOptions.
File
- tests/
src/ Unit/ SelectOrOtherWidgetBaseTest.php, line 157
Class
- SelectOrOtherWidgetBaseTest
- Tests the form element implementation.
Namespace
Drupal\tests\select_or_other\UnitCode
public function testGetSelectedOptions() {
// Mock the widget
$mock = $this
->getMockBuilder('Drupal\\select_or_other\\Plugin\\Field\\FieldWidget\\SelectOrOtherWidgetBase')
->disableOriginalConstructor()
->setMethods([
'getColumn',
'getOptions',
])
->getMockForAbstractClass();
$mock
->expects($this
->any())
->method('getColumn')
->willReturn('id');
$mock
->expects($this
->any())
->method('getOptions')
->willReturnOnConsecutiveCalls([], [
1 => 1,
2 => 2,
3 => 3,
]);
// Mock up some entities.
$entity1 = $this
->getMockForAbstractClass('Drupal\\Core\\Entity\\EntityInterface');
$entity1->id = 1;
$entity2 = $this
->getMockForAbstractClass('Drupal\\Core\\Entity\\EntityInterface');
$entity2->id = 3;
// Put the entities in a mocked list.
$items = $this
->getMockForAbstractClass('Drupal\\Core\\Field\\FieldItemListInterface');
$items
->expects($this
->any())
->method('valid')
->willReturnOnConsecutiveCalls(TRUE, TRUE, FALSE, TRUE, TRUE, FALSE);
$items
->expects($this
->any())
->method('current')
->willReturnOnConsecutiveCalls($entity1, $entity2, $entity1, $entity2);
// Make getSelectedOptions accessible.
$getSelectedOptionsMethod = new ReflectionMethod($this::$testedClassName, 'getSelectedOptions');
$getSelectedOptionsMethod
->setAccessible(TRUE);
$expected = [];
$selected_options = $getSelectedOptionsMethod
->invokeArgs($mock, [
$items,
]);
$this
->assertArrayEquals($expected, $selected_options, 'Selected options without a matching option are filtered out.');
/** @var SelectOrOtherWidgetBase $mock */
$expected = [
1,
3,
];
$selected_options = $getSelectedOptionsMethod
->invokeArgs($mock, [
$items,
]);
$this
->assertArrayEquals($expected, $selected_options, 'Selected options with matching options are kept.');
}