Charlie Fish
Charlie Fish

Reputation: 20546

iOS UITests NSLocalizedString Not Working

I'm trying to localize my UITests to work with other languages (currently using Snapshot to automate screenshots so that's why I need this to work).

My main problem right now is with a Done button in IQKeyboardManager.

In English I have the following code and it works fine:

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

to tap the done button after entering text.

In Spanish that button is called "OK". Looks like it's getting that from some default UIKit localized string or something like that.

I tried adding a .strings file in my UITest es.lproj folder and put "UIBarButtonSystemItem.Done" = "OK"; in it.

I also changed it to be:

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

and that didn't work. Always used "Done".

It always gives the error:

No matches found for "Done" Button.

I also tried:

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

and that resulted in an error:

No matches found for "UIBarButtonSystemItem.Done" Button.

So it looks like my .strings file isn't working for my UITests. Any ideas of how to get it working?

Upvotes: 5

Views: 2400

Answers (2)

NSMutableString
NSMutableString

Reputation: 10743

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()

Upvotes: 2

Titouan de Bailleul
Titouan de Bailleul

Reputation: 12949

I created this small project that supports English and Spanish. The tests can also be run using the two different languages by switching it in the scheme's configuration

enter image description here

This is how the test is build

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

It uses the following function to get the translations

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
}

Here's the project that where you can see it work: https://github.com/TitouanVanBelle/LocalizationUITests

Upvotes: 3

Related Questions