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

女生的网名这么多〃 提交于 2019-11-28 19:35:56

In the UI tests, the main bundle seems to be a random launcher app. That's why the .strings file doesn't appear: even though you added it to your test bundle, NSLocalizedString is checking the wrong bundle. To get around this, you need an invocation like this:

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

Which you might want to pull into a helper method.

Paradise

Here is my solution:

  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: http://stackoverflow.com/questions/33086266/cant-get-access-to-string-localizations-in-ui-test-xcode-7 */
    /*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")]

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!