10

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->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?

1 Answer 1

13

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->getMockBuilder('Drupal\namespace\for\custom_utils\someresolver')
    ->disableOriginalConstructor()
    ->getMock();
  $config_factory = $this->getMockBuilder('Drupal\Core\Config\ConfigFactory')
    ->disableOriginalConstructor()
    ->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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.