"\Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container." I am attempting to write a PHPUnit test for a service of mine.

My test looks like the following.

class CustomServiceTest extends UnitTestCase {

  public function testDefaultBehavior() {
    $service = new CustomService(\Drupal::service('custom_utils.some_resolver'), \Drupal::configFactory());
    $service-&gt;execute();
  }
}


However, it raises the following exception.

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


What am I doing wrong?
You need to mock the services you will be using in your test, so that they return values. You can do that as follows:

public function testDefaultBehavior() {
  $some_resolver = $this-&gt;getMockBuilder('Drupal\namespace\for\custom_utils\someresolver')
    -&gt;disableOriginalConstructor()
    -&gt;getMock();
  $config_factory = $this-&gt;getMockBuilder('Drupal\Core\Config\ConfigFactory')
    -&gt;disableOriginalConstructor()
    -&gt;getMock();
    $service = new CustomService($some_resolver, $config_factory);


}

Note that you should use the actual interface (or class if you have no interface) instead of Drupal\namespace\for\custom_utils\someresolver

You'll need to set up expectations to return the values from the services you mocked. You can read more on that here:

https://www.drupal.org/docs/8/phpunit/understanding-phpunit-expectations