Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get correct string localization when running my unit tests?

I have a project that needs to support French and English. I put all strings into resource files. When I debug the program in Visual Studio, I can successfully view the program in French. However, when I run the tests for the program, the program reverts to English. I added the French resource dll file to the deployment. This allows me to debug individual unit tests in French, but when I click Test -> Debug -> All Tests in Solution, the program runs in English.

I tried to add [DeploymentItem(@"..\bin\x86\Release\fr", "fr-FR")] to one of the tests also, but this didn't help. Does anyone have any suggestions on how to fix this? Thanks!

like image 279
user1438430 Avatar asked Dec 16 '22 21:12

user1438430


1 Answers

I wrap language tests in a using statement like this:

[Test]
public void Loads_correct_labels_from_language()
{
    using(new LanguageSwitchContext("fr"))
    {
       var okayString = MyResources.Okay_Button;
       Assert.Equals("your localized string here", okayString);
    }
}

public class LanguageSwitchContext : IDisposable
{
    public CultureInfo PreviousLanguage { get; private set; }

    public LanguageSwitchContext(CultureInfo culture) 
    {
        PreviousLanguage = System.Threading.Thread.CurrentThread.CurrentCulture;
        System.Threading.Thread.CurrentThread.CurrentCulture = culture;
    }

    public LanguageSwitchContext(string language) 
    {
        //create culture from language
    }

    public void Dispose() 
    {
        System.Threading.CurrentThread.CurrentCulture = PreviousCulture;
    }
}
like image 133
Hadi Eskandari Avatar answered Dec 22 '22 01:12

Hadi Eskandari