Drupal 9: Mocking Configuration For Testing Using A Trait

<?php

namespace Drupal\Tests\mymodule\Traits;

/**
 * Trait to create the module configuration mock.
 */
trait ConfigurationTrait {

  /**
   * Helper method to facilitate the configuration mocking.
   *
   * @param array $passedConfig
   *   Passed configuration items.
   *
   * @return \PHPUnit\Framework\MockObject\MockBuilder
   *   The mocked configuration object.
   */
  public function mockConfiguration(array $passedConfig = []) {
    $defaulConfig = [
      'config' => 'value',
    ];

    $config = ['my_module.settings' => array_merge($defaulConfig, $passedConfig)];

    $configFactory = $this->getConfigFactoryStub($config);

    $configFactory->get('my_module.settings')
      ->expects($this->any())
      ->method('getCacheContexts')
      ->willReturn([]);

    $configFactory->get('my_module.settings')
      ->expects($this->any())
      ->method('getCacheTags')
      ->willReturn([]);

    return $configFactory;
  }

}

Use it like this:

<?php

namespace Drupal\Tests\mymodule\Unit;

use Drupal\Tests\UnitTestCase;
use Drupal\Tests\mymodule\Traits\ConfigurationTrait;

/**
 * Tests for the module service.
 */
class MymoduleTest extends UnitTestCase {
  use ConfigurationTrait;

  public function testConfiguration() {
    // Create configuration item.
    $config = ['config' => 'a different value'];
    $configFactory = $this->mockConfiguration($config);

    // Run tests on configuration.
  }
}

 

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
12 + 0 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.