How to write PHPUnit test for any function that has external dependencies?
The code is dependent on Drupal's service container existing, and thus a container needs to be instantiated and used. This is possible in PHPUnit tests using the \Drupal::setContainer() method, and creating a container object.

use Drupal\Core\DependencyInjection\ContainerBuilder;

protected function setUp() {
  parent::setUp();

  $this-&gt;account = $this
    -&gt;getMockBuilder('Drupal\user\Entity\User')
    -&gt;disableOriginalConstructor()
    -&gt;getMock();

  // Create a new container object.
  $container = new ContainerBuilder();

  // Add a service into it.
  $container-&gt;set('current_user', $this-&gt;account);

  // Let Drupal use your mock container.
  \Drupal::setContainer($container);
}