I'm trying to set up a unit test based on UnitTestCase in Drupal 8 that uses some config variables. Unfortunately I was not able to find a way to insert those config variables into the system in the setup (searched Drupal documentation and any Drupal unit test example involving config), so the function being tested always works with null config and fails. I am trying to test individual functions in isolation, so a browser test is not really appropriate for this.
I have simplified the problem to the minimum code necessary to explain/reproduce the issue. Here are the three components. Where in the mock/setup do I insert the array('bucketName' => 'test_bucket')
and other properties so that it can be read from the tested function?
Function:
public function example() {
return \Drupal::config('my_module.job')->get('my_module.bucketName');
}
Test function:
public function testExample() {
$myModuleHelper = new MyModuleHelper();
$expected_config = array(
'bucketName' => 'test_bucket',
);
$this->assertEquals($expected_config, $myModuleHelper->example());
}
Test setup:
public function setUp() {
$this->config = $this->getMockBuilder('\Drupal\Core\Config\ImmutableConfig')
->disableOriginalConstructor()
->getMock();
$this->configFactory = $this->getMockBuilder('\Drupal\Core\Config\ConfigFactory')
->disableOriginalConstructor()
->getMock();
$this->configFactory->expects($this->any())
->method('get')
->with('my_module.job')
->willReturn($this->config);
$this->container = new ContainerBuilder();
$this->container->set('config.factory', $this->configFactory);
\Drupal::setContainer($this->container);
}
Test response:
null does not match expected type "array".