ios – 具有本地化UI的XCode 7 UITests

前端之家收集整理的这篇文章主要介绍了ios – 具有本地化UI的XCode 7 UITests前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我的应用程序中,我使用NSLocalizedString来本地化我的应用程序.现在我想切换到UITests并像这样使用Testcode:
[tabBarsQuery.buttons["particiants"] tap];

这适用于英语,但不适用于其他语言.

[tabBarsQuery.buttons[NSLocalizedString("PARTICIPANTS",comment:nil)] tap];

失败 – 可能是因为Localizable.strings在另一个包中.如何测试本地化应用?

解决方法

我想实际测试UI功能内容而不仅仅是它们的存在,因此设置默认语言或使用辅助功能标识符是不合适的.

这建立在Volodymyrmatsoftware的答案之上.但是他们的答案依赖于需要在SnapshotHelper中明确设置的deviceLanguage.此解决方案动态获取设备正在使用的实际支持语言.

>将Localizable.strings文件添加到UITest目标.
>将以下代码添加到您的UITest目标:

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.

如果它仍然无法获得捆绑,则返回“?”对于字符串,所以它将失败任何寻找特定字符串的UI测试.

原文链接:https://www.f2er.com/iOS/335141.html

猜你在找的iOS相关文章