SaaS CMS has officially launched! Learn more now.

Mocking LocalizationService



We have been able to mock the localization service with this code:

var providerBasedLocalizationService = new ProviderBasedLocalizationService();

providerBasedLocalizationService.AddProvider(new MemoryLocalizationProvider());

serviceLocator.Setup(l => l.GetInstance()).Returns(providerBasedLocalizationService);
serviceLocator.Setup(l => l.TryGetExistingInstance(out providerBasedLocalizationService)).Returns(true);

However this is not working as of Episerver 11 since TryGetExistingInstance is now an extension method. This wouldn't have been an issue if it wasn't that LocalizationService.Current is using this method, otherwise we could've just removed that setup. 

To mitigate this problem I've replaced all our code calling LocalizationService.Current, but it seems like this code is also called internally by Episerver, e.g. by localized category descriptions.

How can we fix this?

Edited, Jan 09, 2018 19:14

It is the generic variant of TryGetExistingInstance that is an extension method. It will call the non-generic variant which you can mock. Something like:

var providerBasedLocalizationService = new ProviderBasedLocalizationService();
object untypedLocalizationService = providerBasedLocalizationService; 

providerBasedLocalizationService.AddProvider(new MemoryLocalizationProvider());

serviceLocator.Setup(l => l.GetInstance<LocalizationService>()).Returns(providerBasedLocalizationService);
serviceLocator.Setup(l => l.TryGetExistingInstance(typeof(LocalizationService), out untypedLocalizationService )).Returns(true);
Jan 10, 2018 14:57

Worked like a charm! Thank you!

Jan 10, 2018 15:03
This topic was created over six months ago and has been resolved. If you have a similar question, please create a new topic and refer to this one.
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.