无法访问 UI 测试中的字符串本地化 (Xcode 7)

Can't get access to string localizations in UI Test (Xcode 7)

所以我遇到了一些经过验证的文本字段的情况。我正在尝试 运行 一个 UI 测试,当他们失败时,他们会收到一条弹出错误消息的警报(可能是一条不同的消息,具体取决于哪些字段无效以及以何种方式无效) .

我想测试不仅显示了警报,而且显示了正确的消息。我遇到的问题是我需要获取本地化文本进行比较(如果我 运行 使用英语以外的另一种语言进行测试),但是当我在 UITest 中调用 NSLocalizedString 时它可以' t 收集正确的本地化字符串(只是 returns 键 [默认])

我试过将 localizeable.strings 文件添加到 UI 测试目标,但没有成功。有谁知道这是否可能?

作为旁注编辑: 我还尝试在 UIAlertView 上设置可访问性标识符,但是当我使用该可访问性标识符进行查询时,它不存在,我只能使用似乎倒退的警报标题来查询它。

在 UI 测试中,主捆绑包似乎是一个随机启动器应用程序。这就是 .strings 文件没有出现的原因:即使您将它添加到测试包中,NSLocalizedString 也会检查错误的包。要解决这个问题,您需要这样的调用:

NSLocalizedString("LOCALIZATION_KEY", bundle: NSBundle(forClass: AClassInYourUITests.self), comment: "")

您可能希望将其引入辅助方法。

这是我的解决方案:

  1. 在您的 UI 测试目标 -> 构建阶段 -> 复制捆绑资源中,添加所需的本地化文件(例如 Localizable.strings)。

  2. 添加类似下面的函数:

    func localizedString(key:String) -> String {
        /*1*/ let localizationBundle = NSBundle(path: NSBundle(forClass: /*2 UITestsClass*/.self).pathForResource(deviceLanguage, ofType: "lproj")!) 
        /*3*/ let result = NSLocalizedString(key, bundle:localizationBundle!, comment: "") // 
        return result
    }
    
    
    /*1 Gets correct bundle for the localization file, see here:  */
    /*2 Replace this with a class from your UI Tests*/ 
    /*3 Gets the localized string from the bundle */
    
  3. 像这样使用函数:app.buttons[localizedString("localized.string.key")]