Drupal - Injecting configuration into mock config object

Your mock of the Config object needs to also have a ::get method and return the appropriate value using your array. The core UnitTestCase class provides ::getConfigFactoryStub(array $configs), which does all of this automatically.

In your setup, create the config factory like this:

$this->configFactory = $this->getConfigFactoryStub([
  'mymodule.job' => ['bucketName' => 'test_bucket'],
]);

Unfortunately, the mocked config does not quite work like a real config object; namely, it doesn't accept dotted keys but only top-level keys. The following will not work:

$this->configFactory = $this->getConfigFactoryStub([
  'mymodule.settings' => [
    'key' => [
      'subkey' => [
        'subsubkey' => 'value',
      ],
    ],
  ],
]);
$this->container = new ContainerBuilder();
$this->container->set('config.factory', $this->configFactory);
\Drupal::setContainer($this->container);

\Drupal::config('mymodule.settings')->get('key.subkey.subsubkey');

This bug report shows a workaround: https://www.drupal.org/node/2862248

Tags:

Testing

8