How do I get an instance of AccountInterface in my Unit Test I want to write a Unit test. But the class I want to test has a AccountInterface dependencie Injection.

When I try to get the AccountInterface Object I get:


  Drupal\Core\DependencyInjection\ContainerNotInitializedException:
  \Drupal::$container is not initialized yet. \Drupal::setContainer()
  must be called with a real container.


My test looks like this

&lt;?php
namespace Drupal\mymodule\test;

use Drupal\mymodule\MyModuleQuery;
use Drupal\Tests\UnitTestCase;
use Drupal\user\Entity\User;

class MyModuleQueryTest extends UnitTestCase {

  protected $user;

  public function __construct() {
    $this-&gt;user = \Drupal::currentUser();
  }

  public function testResult() {
    $MyModuleQuery = new MyModuleQuery(1, $this-&gt;user);
    $countUser = $MyModuleQuery-&gt;mymodule_get_user();
    $countNode = $MyModuleQuery-&gt;mymodule_get_node();        
    $bool = FALSE;
    if (!isset($countNode) &amp;&amp; !isset($countUser)) {
      $bool = TRUE;
    }
    $this-&gt;assertTrue($bool);
  }
}
You most likely want to mock your dependencies rather than trying to instantiate actual objects because a unit test should only test the class it describes. However this is not always as convenient.

In this case you are trying to call the \Drupal::currentUser static method which is dependent on the dependency injection container. An empty container can be created and used for the test, and test doubles available for it.

protected function setUp() {
  // use Drupal\Core\DependencyInjection\ContainerBuilder;
  $container = new ContainerBuilder();
  $account = $this-&gt;prophesize('Drupal\Core\Session\AccountProxyInterface');
  $container-&gt;set('current_user', $account-&gt;reveal());
  \Drupal::setContainer($container);
  $this-&gt;user = \Drupal::currentUser();
}


However you do not actually need the container, and can just use the test double.

public function testResult() {
  $accountProphecy = $this-&gt;prophesize('\Drupal\Core\Session\AccountProxyInterface');
  // Mock some methods.
  // $accountProphecy-&gt;getUserName()-&gt;willReturn('admin');
  $MyModuleQuery = new MyModuleQuery(1, $accountProphecy-&gt;reveal());
}