learning swift and other stuff

NSLocalizedString in XCTest

Published December 2020

let's say you want to run your Tests in multible languages i.e. for your Test your use to capture your screenshot with fastlane.

often you'll have some static texts to identify something to tap

app.tables.buttons["Text löschen"].tap()

obviuosly this will only work when you are running your test in german.

So how do we get this working in english?

First thing that will come to mind: well then let's do this with NSLocalizedString instead.

For this we assume you have configured another language for your project (english) and your Loalizable.strings is all set and translates "Text löschen" to "copy text")

app.tables.buttons[NSLocalizedString("Text löschen", comment: "Text löschen")].tap()

We expected it will look for "copy text" now. But surprise: This is not working. Your test still can't find "Text löschen"

This is because NSLocalizedString uses the Bundle.main to look up translation. Using Bundle.main does not work when running UITests because it gives you the bundle of the UITest Runner App instead of the bundle of your UITest.

to get this working we have to do two things:

1. use our test bundle for NSLocalizedString

we tell NSLocalizedString to use another bundle: Our test bundle. To get the bundle of our Test we use Bundle(for: self.classForCoder) in our test class.

let cellIdentifier = NSLocalizedString("Text löschen", bundle: Bundle(for: self.classForCoder), comment: "")
app.tables.buttons[cellIdentifier].tap()

2. make Loalizable.strings available to your Tests

Find Loalizable.strings in your project an toggle Target Membership for your Test target