4

我正在尝试本地化我的 UITests 以使用其他语言(目前使用 Snapshot 来自动化屏幕截图,这就是我需要它工作的原因)。

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

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

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

输入文本后点击完成按钮。

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

我尝试在我的 UITestes.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。关于如何让它工作的任何想法?

4

2 回答 2

2

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

在此处输入图像描述

这就是测试的构建方式

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

于 2017-07-10T05:37:35.557 回答
0

Just for the reference and easy lookup:

It is indeed because you cannot access your main bundle from your UITests target.

let testBundle = Bundle(for: type(of: self ))
let lookup = NSLocalizedString("UIBarButtonSystemItem.Done", bundle: testBundle, value: "Done", comment: "")
app.toolbars.buttons[lookup].tap()
于 2020-05-13T11:56:30.497 回答