Don't miss out Virtual Happy Hour this Friday (April 26).

Try our conversational search powered by Generative AI!

Unit testing and LocalizationService problems

Vote:
 

Hi all,

I am currently writing some tests for fluent validation.  My validation rules use the LocalizationService to obtain the error messages to display.

This all works perfectly well.  However when I run my test, the LocalizationService is null.  After researching this, i discovered that the LocalizationService contains many static methods which of course is going to be difficult to test.

I've read that some people have written wrapper classes etc, but I am a bit unclear on how to approach this.

Has anyone any advice as to how I can implement LocalizationService for unit tests?

Thanks in advance,

Adam

#117377
Feb 19, 2015 13:19
Vote:
 

Hi

There is a MemoryLocalizationService provided that is designed to be used in unit test. Perhaps you can use that to solve your issues?

Regards

Per Gunsarfs

#117380
Feb 19, 2015 15:39
Vote:
 

Hi Per, thanks for your quick reply.

After reading your reply I have two further questions that you might be able to help me with:

1) Have you any code examples of the MemoryLocalizationService in use?  There doesn't appear to be much out there when running a search.

2) Should we be using MemoryLocalizationService in all of our code (replacing LocalizationService), or just for the unit tests that we write?

Thanks

Adam

#117381
Feb 19, 2015 16:00
Vote:
 

Well, it depends on how your classes are written, and also how you are writing your tests.

But no, you should not depend on the MemoryLocalizationService in all your code. Rather, when the site is running normally, the service locator will supply the default localization service. And when you want to test your code you would explicitly supply a MemoryLocalizationService to your classes. If you are dependent on what the service returns, you can configure your MemoryLocalizationService in your test setup.

This assuming that you are unit testing your own classes. If you want to make integration tests that runs through large parts of the application I would suggest setting up the default service with controlled data.

Regards

Per Gunsarfs

#117383
Feb 19, 2015 16:12
Vote:
 

For 2), I second Per that you should not use MemoryLocalizationService in all your code. It should be use in your unit tests only. For 1), you can simply do this:

MemoryLocalizationService _localizationService = new MemoryLocalizationService();
_localizationService.AddString(CultureInfo.CurrentUICulture, "<key>", "<value>");

Then now your code calls to LocalizationService will be supplied with the data you add here.
Regards.
/Q
#117417
Feb 20, 2015 11:15
* 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.