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

17

我有几个需要验证的文本字段。现在我想运行一个UI测试,如果它们验证失败,就会弹出一个警示框,显示错误信息(根据哪些字段是无效的及其方式而可能显示不同的消息)。

我希望测试的不仅是警示框的出现,还包括正确的信息是否被显示。但我的问题是,我需要获得本地化文本进行比较(如果我在英语以外的其他语言中运行测试),但当我在UITest中调用NSLocalizedString时,它无法获取正确的本地化字符串(只返回键[默认])。

我尝试将localizeable.strings文件添加到UITest目标中,但没有成功。请问是否有人知道这是否可行?

另外补充一下:我还尝试在UIAlertView上设置可访问标识符,但当我使用该可访问标识符查询时,它不存在,我只能使用警报的标题来查询,这似乎有些奇怪。


我发现的一个解决方法是强制应用程序以英语启动(启动参数),然后针对英语字符串进行测试。虽然可行,但不是最优解决方案。 - ssrobbi
3个回答

20
在UI测试中,主Bundle似乎是一个随机的启动器应用程序。这就是为什么.strings文件不会出现的原因:尽管你已将其添加到测试Bundle中,但NSLocalizedString正在检查错误的Bundle。要解决这个问题,你需要使用以下调用方式:

在UI测试中,主Bundle看起来像是一个随机的启动应用程序。这就是为什么.strings文件不会出现的原因:即使您将其添加到测试Bundle中,NSLocalizedString也会检查错误的Bundle。要解决这个问题,您需要使用以下调用方式:

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

也许您想将其提取到一个助手方法中。


8
我复制了与Localizable.strings对应的资源包,但无论设备使用哪种语言,我始终只得到该键的英文版本。有任何想法吗,@Manuel? - Matias

6
这是我的解决方案:
  1. In your UI Tests target -> Build Phases -> Copy Bundle Resources, add the needed localization files (e.g. Localizable.strings).

  2. Add a function similar to the following:

    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: https://dev59.com/zFwY5IYBdhLWcg3wCUA7 */
    /*2 Replace this with a class from your UI Tests*/ 
    /*3 Gets the localized string from the bundle */
    
  3. Use the function like this: app.buttons[localizedString("localized.string.key")]


动态获取设备语言不可能吗?我不喜欢需要指定设备语言的想法。UITest类没有与正在测试的设备建立连接并从中获取本地化信息的感觉吗? - Sti

0
我这里还有另一种方法:https://dev59.com/F1wX5IYBdhLWcg3wnwgy#75178860。在问题被删除/关闭时可以复制粘贴使用。

Different approach without calling methods on your String

Prerequisites

You are using NSLocalizedString.

Step 1

Make sure you add the translations to your test targets (Go to your Localizable file and on the right side you can tap your UI test targets).

Step 2

Add this somewhere in your main target

#if DEBUG
    // Can be changed by UI tests to get access to localized content
    var bundleForLocalizedTexts = Bundle.main
#else
    let bundleForLocalizedTexts = Bundle.main
#endif 

Step 3

Add this value to the parameter bundle in all your NSLocalizedStrings, like this:

NSLocalizedString(
    "localized",
    bundle: bundleForLocalizedTexts,
    comment: ""
)

Step 4

Override the method setUp in your XCTestCase subclass and add this line:

bundleForLocalizedTexts = Bundle(for: MySubclass.self)

Step 5

Everything should work! All languages should work, no extra methods to call.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接