2

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.

1

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);
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.