Godfather
Godfather

Reputation: 4340

Get localized strings from main bundle

How do i get inside the UITest target localizations from the main Bundle?

func localizedText(_ key: String) -> String {
    return Bundle.main.localizedString(forKey: key, value: nil, table: nil)
}

I tried accessing Bundle.main but isn't localizing the string. And it seems i can't import the main target of the app to do Bundle(for: ClassName.self).localized...

Any hints?

Upvotes: 4

Views: 3218

Answers (1)

joern
joern

Reputation: 27620

To use your localized strings in UITests you have to do two things:

1) Add your Localizable.strings file to your UITest target

2) Access the string via the UITest bundle:

func localizedText(_ key: String) -> String {
    let uiTestBundle = Bundle(for: AClassFromYourUITests.self)
    return NSLocalizedString(key, bundle: uiTestBundle, comment: "")
}

Just make sure that you use a class that is part of your UITest target to access the bundle.

Using Bundle.main does not work when running UITests because it gives you the bundle of the UITest Runner App instead of the UITest bundle

Upvotes: 7

Related Questions