Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在运行单元测试时,如何获得正确的字符串本地化?_C#_Testing_Localization_Resource File - Fatal编程技术网

C# 在运行单元测试时,如何获得正确的字符串本地化?

C# 在运行单元测试时,如何获得正确的字符串本地化?,c#,testing,localization,resource-file,C#,Testing,Localization,Resource File,我有一个项目,需要支持法语和英语。我将所有字符串放入资源文件中。当我在Visual Studio中调试该程序时,我可以成功地用法语查看该程序。但是,当我为程序运行测试时,程序将恢复为英语。我将法语资源dll文件添加到部署中。这允许我用法语调试单个单元测试,但当我单击Test->debug->All tests in Solution时,程序以英语运行 我还试图将[DeploymentItem(@..\bin\x86\Release\fr”,“fr-fr”)]添加到其中一个测试中,但这没有帮助。有

我有一个项目,需要支持法语和英语。我将所有字符串放入资源文件中。当我在Visual Studio中调试该程序时,我可以成功地用法语查看该程序。但是,当我为程序运行测试时,程序将恢复为英语。我将法语资源dll文件添加到部署中。这允许我用法语调试单个单元测试,但当我单击Test->debug->All tests in Solution时,程序以英语运行


我还试图将[DeploymentItem(@..\bin\x86\Release\fr”,“fr-fr”)]添加到其中一个测试中,但这没有帮助。有人对如何解决这个问题有什么建议吗?谢谢

我将语言测试包装在一个using语句中,如下所示:

[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;
    }
}

这里有两个潜在问题:

  • 运行测试时,
    CurrentUICulture
    可能未设置为要测试的语言
  • 附属程序集(在您的示例中仅为法语)可能不会部署在单元测试环境中。当ResourceManager找不到与UI区域性匹配的附属程序集时,它默认为嵌入在项目DLL本身中的基础语言(因此您可以使用英语,假设这是您的基础语言)
  • 1。您可以确保设置
    System.Threading.CurrentThread.CurrentUICulture=new CultureInfo(“fr”)在测试中或在测试类初始化时


    两个人。像您提到的那样使用
    DeploymentItemAttribute
    应该可以工作。请验证以法语成功运行应用程序时部署的附属程序集是否以相同的名称复制到测试部署中的相同子文件夹中。它可能更像是
    [DeploymentItem(@“bin\fr”,“fr fr”)]

    我并不是在做语言测试。该项目具有贯穿代码的测试,以确保其正常工作。我希望有一种简单的方法可以用多种语言测试代码,以确保本地化不会破坏程序。你有什么样的测试?如果使用NUnit,则可以使用SetCultureAttribute使用特定区域性运行测试,这将确保使用该区域性执行测试中的代码。请参见此处:@Hadi,您正在使用
    System.Threading.CurrentThread.CurrentCulture
    ,但这不会影响本地化(它会影响依赖于区域性的格式设置和解析)。您还应该设置
    System.Threading.CurrentThread.CurrentUICulture