Problem/Motivation
Experienced an odd behavior this morning. Given the following setUp() method.
TestHelpers::service('module_handler', NULL, NULL, ['moduleExists'])
->method('moduleExists')->willReturnCallback(function () {
return $this->moduleExists;
});
TestHelpers::service('lm_utilities.routing', RoutingUtilities::class, NULL, ['getEntityFromRoute'])
->method('getEntityFromRoute')->willReturnCallback(function () {
return $this->node;
});
TestHelpers::setServices([
'entity_type.manager' => NULL,
'lm_utilities.form' => FormUtilities::class,
'string_translation' => NULL,
]);
And the following test case.
$this->node = TestHelpers::saveEntity(Node::class, ['title' => 'Test Node', 'status' => '1']);
$hook_handler = TestHelpers::createClass(HookHandler::class);
// The method below calls RoutingUtilities::getEntityFromRoute().
$hook_handler->testBlockContentEntityBuilder();
Which results in the following error
Trying to call method getEntityTypeId() on NULL.
Further inspection shows that the mocked RoutingUtilities::getEntityFromRoute()
is not picking up the correct $node
value.
Known Workaround
If I move
TestHelpers::service('lm_utilities.routing', RoutingUtilities::class, NULL, ['getEntityFromRoute'])
->method('getEntityFromRoute')->willReturnCallback(function () {
return $this->node;
});
out of the setUp() method and to the test method and refactor as below
$node = TestHelpers::saveEntity(
Node::class,
[
'title' => 'Test Node',
'type' => 'test',
'status' => '1',
]
);
TestHelpers::service('lm_utilities.routing', RoutingUtilities::class, TRUE, ['getEntityFromRoute'])
->method('getEntityFromRoute')->willReturn($node);
then the test passes as expected.
The odd thing is that the ModuleHandler::moduleExists
service mock works as expected. Setting $this->moduleExists
to true or false gets picked up by the mocked method callback. I'm wondering if there is a bug in TestHelpers::service()
or TestHelpers::setServices()
where callback functions are not getting updated values from TestHelpers::saveEntity()