TransWikia.com

How do I change the current language in a Kernel test?

Drupal Answers Asked on November 28, 2021

I’m writing a test for something that returns a Url from an entity. This should be language-aware, so the test needs to change the current language.

I started off writing a Kernel test for this, because they’re faster, but I can’t figure out how to make the test code change the current language:

  public static $modules = [
    'system',
    'user',
    'language',
    'content_translation',
    [SNIP]
  ];

  protected function setUp() {
    parent::setUp();

    $this->installConfig(['language']);
    $this->installEntitySchema('configurable_language');


    $this->languages['de'] = ConfigurableLanguage::createFromLangcode('de');
    $this->languages['de']->save();

    $config = $this->config('language.negotiation');
    $config->set('url.prefixes', [
      'en' => 'en',
      'de' => 'de',
    ])->save();

    Drupal::service('kernel')->rebuildContainer();
    Drupal::service('router.builder')->rebuild();
    $this->languageManager = $this->container->get('language_manager');
    $this->languageManager->reset();

    [SNIP]
  }

  public function testCurrentLanguageChange() {
    // Change the site's current language.
    dump(Drupal::languageManager()->getCurrentLanguage());

    Drupal::service('language.default')->set($this->languages['de']);

    dump(Drupal::languageManager()->getCurrentLanguage());
  }

}

In the test code above, both dump() calls output the ‘English’ language object.

One Answer

Looks like I needed to call:

    Drupal::languageManager()->reset();

No, wait, that doesn't seem to be the whole story.... ARGH.

EDIT:

For the entity to be treated as translatable and so return the right URL, I also needed to set the bundle as translatable:

    $this->entityTypeManager->getStorage('language_content_settings')->create([
      'target_entity_type_id' => 'node',
      'target_bundle' => 'page',
    ])->save();
    $this->container->get('content_translation.manager')->setEnabled('node', 'page', TRUE);

Answered by joachim on November 28, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP