2012-01-20 138 views
6

我們的應用程序中有幾千個本地化字符串。我希望創建一個單元測試來遍歷所有鍵和所有支持的語言,以確保每種語言都具有默認(英語)resx文件中的每個鍵。單元測試本地化字符串

我的想法是使用Reflection從Strings類中獲取所有密鑰,然後使用ResourceManager比較每種語言中每個鍵的檢索值並進行比較以確保其與英文版不匹配,但是當然,在多種語言中有些詞彙是相同的。

有沒有辦法檢查ResourceManager是否從衛星組件獲得了它的值與默認的資源文件?

調用示例:

string en = resourceManager.GetString("MyString", new CultureInfo("en")); 
string es = resourceManager.GetString("MyString", new CultureInfo("es")); 

//compare here 

回答

8

調用ResourceManager.GetResourceSet方法得到的中性和本地化的文化的所有資源,然後比較這兩個集合:

ResourceManager resourceManager = new ResourceManager(typeof(Strings)); 
IEnumerable<string> neutralResourceNames = resourceManager.GetResourceSet(CultureInfo.InvariantCulture, true, false) 
    .Cast<DictionaryEntry>().Select(entry => (string)entry.Key); 
IEnumerable<string> localizedResourceNames = resourceManager.GetResourceSet(new CultureInfo("es"), true, false) 
    .Cast<DictionaryEntry>().Select(entry => (string)entry.Key); 

Console.WriteLine("Missing localized resources:"); 
foreach (string name in neutralResourceNames.Except(localizedResourceNames)) 
{ 
    Console.WriteLine(name); 
} 

Console.WriteLine("Extra localized resources:"); 
foreach (string name in localizedResourceNames.Except(neutralResourceNames)) 
{ 
    Console.WriteLine(name); 
} 
+0

這是完美的,邁克爾!謝謝! –