具有本地化UI的Xcode 7 UITests [英] Xcode 7 UITests with localized UI
问题描述
在我的应用程序中,我正在使用NSLocalizedString
本地化我的应用程序.现在,我想切换到UITests
并像这样使用habe Testcode:
In my App I'm using NSLocalizedString
to localize my app. Now I want to switch to UITests
and habe Testcode like this:
[tabBarsQuery.buttons["particiants"] tap];
这适用于英语,但不适用于其他语言.
This works for English but fails for other languages.
[tabBarsQuery.buttons[NSLocalizedString("PARTICIPANTS",comment:nil)] tap];
失败-可能是因为Localizable.strings在另一个捆绑包中.如何测试本地化的应用程序?
Fails - probably because Localizable.strings is in another bundle. How can I test a localized app?
推荐答案
我想实际测试UI功能的内容,而不仅仅是它们的存在,因此设置默认语言或使用可访问性标识符都不适合.
I wanted to actually test the content of UI features and not just their existence, so setting a default language or using the accessibility identifiers wouldn't suit.
这基于 Volodymyr 和
This builds on Volodymyr's and matsoftware's answers. However their answers rely on deviceLanguage
which needs to be explicitly set in SnapshotHelper
. This solution dynamically gets the actual supported language the device is using.
- 将
Localizable.strings
文件添加到UITest目标. -
将以下代码添加到您的UITest目标:
- Add the
Localizable.strings
files to your UITest target. Add the following code to your UITest target:
var currentLanguage: (langCode: String, localeCode: String)? {
let currentLocale = Locale(identifier: Locale.preferredLanguages.first!)
guard let langCode = currentLocale.languageCode else {
return nil
}
var localeCode = langCode
if let scriptCode = currentLocale.scriptCode {
localeCode = "\(langCode)-\(scriptCode)"
} else if let regionCode = currentLocale.regionCode {
localeCode = "\(langCode)-\(regionCode)"
}
return (langCode, localeCode)
}
func localizedString(_ key: String) -> String {
let testBundle = Bundle(for: /* a class in your test bundle */.self)
if let currentLanguage = currentLanguage,
let testBundlePath = testBundle.path(forResource: currentLanguage.localeCode, ofType: "lproj") ?? testBundle.path(forResource: currentLanguage.langCode, ofType: "lproj"),
let localizedBundle = Bundle(path: testBundlePath)
{
return NSLocalizedString(key, bundle: localizedBundle, comment: "")
}
return "?"
}
通过localizedString(key)
对于具有脚本代码的语言,localeCode
将为langCode-scriptCode
(例如,zh-Hans
).否则,localeCode
将为langCode-regionCode
(例如,pt-BR
). testBundle
首先尝试通过localeCode
解析lproj,然后回退到langCode
.
For those languages with a script code, the localeCode
will be langCode-scriptCode
(for example, zh-Hans
). Otherwise the localeCode
will be langCode-regionCode
(for example, pt-BR
). The testBundle
first tries to resolve the lproj by localeCode
, then falls back to just langCode
.
如果仍然无法获取捆绑包,则返回?"字符串,因此它将在寻找特定字符串的所有UI测试中失败.
If it still can't get the bundle, it returns "?" for the string, so it will fail any UI tests that look for specific strings.
这篇关于具有本地化UI的Xcode 7 UITests的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!