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