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,
There is a MemoryLocalizationService provided that is designed to be used in unit test. Perhaps you can use that to solve your issues?
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?
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.
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