ModuleImplementsAlterTest.php in Drupal 9        
                          
                  
                        
  
  
  
  
File
  core/tests/Drupal/KernelTests/Core/Extension/ModuleImplementsAlterTest.php
  
    View source  
  <?php
namespace Drupal\KernelTests\Core\Extension;
use Drupal\KernelTests\KernelTestBase;
class ModuleImplementsAlterTest extends KernelTestBase {
  
  protected static $modules = [
    'system',
  ];
  
  public function testModuleImplementsAlter() {
    
    $module_handler = \Drupal::moduleHandler();
    $this
      ->assertSame(\Drupal::moduleHandler(), $module_handler, 'Module handler instance is still the same.');
    
    \Drupal::service('module_installer')
      ->install([
      'module_test',
    ]);
    
    $this
      ->assertNotSame(\Drupal::moduleHandler(), $module_handler, 'The \\Drupal::moduleHandler() instance has been replaced during \\Drupal::moduleHandler()->install().');
    
    $this
      ->assertTrue(function_exists('module_test_modules_installed'), 'The file module_test.module was successfully included.');
    $this
      ->assertArrayHasKey('module_test', \Drupal::moduleHandler()
      ->getModuleList());
    $this
      ->assertContains('module_test', \Drupal::moduleHandler()
      ->getImplementations('modules_installed'), 'module_test implements hook_modules_installed().');
    $this
      ->assertContains('module_test', \Drupal::moduleHandler()
      ->getImplementations('module_implements_alter'), 'module_test implements hook_module_implements_alter().');
    
    $this
      ->assertFalse(function_exists('module_test_altered_test_hook'), 'The file module_test.implementations.inc is not included yet.');
    
    $this
      ->assertContains('module_test', \Drupal::moduleHandler()
      ->getImplementations('altered_test_hook'), 'module_test implements hook_altered_test_hook().');
    
    $this
      ->assertTrue(function_exists('module_test_altered_test_hook'), 'The file module_test.implementations.inc was included.');
  }
  
  public function testModuleImplementsAlterNonExistingImplementation() {
    
    \Drupal::service('module_installer')
      ->install([
      'module_test',
    ]);
    
    $this
      ->expectException(\RuntimeException::class);
    $this
      ->expectExceptionMessage('An invalid implementation module_test_unimplemented_test_hook was added by hook_module_implements_alter()');
    \Drupal::moduleHandler()
      ->getImplementations('unimplemented_test_hook');
  }
}