Drupal - How to mock a node field value for phpunit?
The following should work using PHPUnit Mock Objects as in your example.
First mock FieldItemListInterface __get magic method.
$fieldDescMock = $this->getMockBuilder('\Drupal\Core\Field\FieldItemListInterface')
->disableOriginalConstructor()
->getMock();
$fieldDescMock->expects($this->any())
->method('__get')
->with('value')
->willReturn('blah');
Then mock the Node/ContentEntityBase __get magic method.
$node->expects($this->any())
->method('__get')
->with('field_description')
->willReturn($fieldDescMock);
Mradcliffe's answer worked for me, here's my example code:
Here's what ended up working for me:
$this->node = $this->getMockBuilder(Node::class)
->disableOriginalConstructor()
->getMock();
$fieldAdsEnabled = $this->getMockBuilder(FieldItemListInterface::class)
->disableOriginalConstructor()
->getMock();
$fieldAdsEnabled->expects($this->any())
->method('__get')
->with('value')
->willReturn(1);
$this->node->expects($this->any())
->method('__get')
->with('field_widgets_enabed')
->willReturn($fieldAdsEnabled);
Note: for me using Node object and not NodeInterface helped. I suspect because otherwise __get isn't available.