I'm trying to get a mock of current user.
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
For this I extend UnitTestCase
class and loading the methods of class User
.
$methods = get_class_methods('\Drupal\user\Entity\User');
Now, as load
function also exists in this User
class, I have created a mock of this User
class and disabling its constructor and setting all methods of this class including load
method which I actually need.
$user = $this->getMockBuilder('\Drupal\user\Entity\User')
->disableOriginalConstructor()
->setMethods($methods)
->getMock();
Since the method is set now, I'm trying to call this method once and not sure what it will return exactly.
$user->expects($this->once())
->method('load')
->will($this->returnValue('admin'));
Now, while running this test, I got 1 error:
Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: You have requested a non-existent service "entity.manager".
Now, my question of interest is what's the need of injecting service entity.manager
?? Although load
is a method of entity storage interface
and also it exists in User
class too. Then why this error coming up?
Can I load current user without mocking entity.manager
class or entity storage interface
?
Actual function for which I'm doing unit testing is:
public static function get_ctype_field_value($field) {
$user = user_load(\Drupal::currentUser()->id());
$ulm = get_type_id($user); // another function in some class, return value 445
$local_market = \Drupal\node\Entity\Node::load($ulm);
$llf = '';
if ($local_market) {
// Get the field value from the LM.
if ($local_market->hasField($field)) {
$localmarket_field = $local_market->$field->value;
}
}
return $localmarket_field;
}