iOS UITests NSLocalizedString不工作

时间:2017-07-06 21:38:37

标签: ios swift localization xcode-ui-testing iqkeyboardmanager

我正在尝试将我的UITests本地化以与其他语言一起使用(目前使用Snapshot来自动执行屏幕截图,这就是我需要这样做的原因)。

我现在的主要问题是IQKeyboardManager中的完成按钮。

在英语中我有以下代码,它工作正常:

app.toolbars.buttons["Done"].tap()

在输入文字后点击完成按钮。

在西班牙语中,该按钮被称为“确定”。看起来它是从一些默认的UIKit本地化字符串或类似的东西得到的。

我尝试在我的UITest es.lproj文件夹中添加.strings文件并将"UIBarButtonSystemItem.Done" = "OK";放入其中。

我也改为:

app.toolbars.buttons[NSLocalizedString("UIBarButtonSystemItem.Done", bundle: Bundle.main, value: "Done", comment: "")].tap()

这不起作用。始终使用“完成”。

总是会出错:

  

找不到“完成”按钮的匹配项。

我也尝试过:

app.toolbars.buttons[NSLocalizedString("UIBarButtonSystemItem.Done", comment: "")].tap()

导致错误:

  

找不到“UIBarButtonSystemItem.Done”按钮的匹配项。

所以看起来我的.strings文件不能用于我的UITests。有关如何使其发挥作用的任何想法吗?

2 个答案:

答案 0 :(得分:1)

我创建了这个支持英语和西班牙语的小项目。通过在方案的配置中切换它,也可以使用两种不同的语言运行测试

enter image description here

这是测试的构建方式

func testExample() {
    let greeting = localizedString(key: "Greetings.Hello")
    XCTAssert(XCUIApplication().staticTexts[greeting].exists, "Expected \"\(greeting)\" label to exist")
}

它使用以下函数来获取翻译

func localizedString(key:String) -> String {
    let bundle = Bundle(for: LocalizationUITests.self)
    let deviceLanguage = Locale.preferredLanguages[0]
    let localizationBundle = Bundle(path: bundle.path(forResource: deviceLanguage, ofType: "lproj")!)
    let result = NSLocalizedString(key, bundle:localizationBundle!, comment: "") //
    return result
}

以下是您可以看到它工作的项目:https://github.com/TitouanVanBelle/LocalizationUITests

答案 1 :(得分:0)

仅供参考和简单查找:

这确实是因为您无法从UITests目标访问主捆绑包。

let testBundle = Bundle(for: type(of: self ))
let lookup = NSLocalizedString("UIBarButtonSystemItem.Done", bundle: testBundle, value: "Done", comment: "")
app.toolbars.buttons[lookup].tap()