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.