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 load the User
class methods.
$methods = get_class_methods('\Drupal\user\Entity\User');
Since load()
is a User
class method, I have created a mock of the User
class, disabled its constructor, and set all methods of this class, including load()
which is the method 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 an error.
Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: You have requested a non-existent service "entity.manager".
What's the need of injecting the entity.manager service?
Although load()
is a method of the entity storage interface, it also exists in the User
class.
Why does this error come up?
Can I load the current user without mocking the entity.manager class?
The actual method for which I'm doing unit testing is the following.
public static function get_ctype_field_value($field) {
$user = user_load(\Drupal::currentUser()->id());
$ulm = get_type_id($user);
$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;
}