I'm working on a project where we need to have code coverage using phpunit. I have a public method that includes this code:
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
foreach ($items as $delta => $item) {
$elements[$delta] = $this->viewValue($item);
}
return $elements;
}
and dependent private method:
/**
* Generate the output appropriate for one field item.
*
* @param \Drupal\Core\Field\FieldItemInterface $item
* One field item.
*
* @return string
* The textual output generated.
*/
protected function viewValue(FieldItemInterface $item) {
$frequency = $item->getValue();
return [
'#theme' => 'frequency',
'#frequency' => $this->switchWeights($frequency['value']),
'#limit' => 5,
];
}
I am trying to cover with unit test the parent method to make sure that it works as suspected. Here my code with no items provided to field to be formatted just covered with abstract class mock:
/**
* Simple test to cover FrequencyFieldFormatter class.
*
* @group my_custom_module_name
*/
class FrequencyFieldFormatterTest extends UnitTestCase {
/**
* Test viewElements function.
*/
public function testviewElements() {
/** @var \Drupal\Core\Field\FieldItemList|\PHPUnit\Framework\MockObject\MockObject $field_list */
$field_list = $this
->getMockBuilder(FieldItemListInterface::class)
->getMockForAbstractClass();
$resultElements = FrequencyFieldFormatter::viewElements($field_list, 'und');
$this->assertEmpty($resultElements);
}
}
When i trying to change assertion to make sure that items field_items processed to be rendered with custom theme but i am facing difficulty when instead providing a mock for abstract class which is specified as interface i providing a mock for real class \Drupal\Core\Field\FieldItemList:
$field_list = $this
->getMockBuilder(\Drupal\Core\Field\FieldItemList::class)
->getMock();
I know that the error i am getting in this case is related to not initialized container for this stack:
There was 1 error:
1) Drupal\Test\my_custom_module_name\Unit\FrequencyFieldFormatterTest::testviewElements
ArgumentCountError: Too few arguments to function Drupal\Core\TypedData\TypedData::__construct(), 0 passed in /Users/username/Sites/drupal-site-09/code/vendor/phpunit/phpunit/src/Framework/MockObject/Generator.php on line 607 and at least 1 expected
Then i tried to initialize container to make it works but i do not know how to do it properly.
May somebody help me?