Distinguishing first launch on UI Tests

463 Views Asked by At

I want to use Fastlane Snapshot in order to generate screenshots for my app. But the behavior of the app is different when launch for the first time and launching after that. How do I manage to get a consistent behavior in order to grab the screenshots? (this question is also relevant for any UI test desired consistency I presume)

1

There are 1 best solutions below

2
On

You should be using UserDefaults class to preserve data in your app so that you can stub data in your tests.

If we assume that the Bool key you use to see if it's the first launch is isFirstTime, in order to stub it in your UI test, you should pass it to launchArguments following the value YES or NO (for Bool values). Note that I added - sign before key, this is the way it works:

class FirstTimeLaunchTest: XCTestCase {

    let app = XCUIApplication()

    override func setUp() {
        super.setUp()
        continueAfterFailure = false

        app.launchArguments += ["-isFirstTime", "YES"]
        app.launch()
    }

    func testWelcomeScreenShown() {
        XCTAssert(app.navigationBars["Welcome"].exists)
    }
}

For tests where you'd like to have first start skipped, use this class:

class LaterLaunchesTest: XCTestCase {

    let app = XCUIApplication()

    override func setUp() {
        super.setUp()
        continueAfterFailure = false

        app.launchArguments += ["-isFirstTime", "NO"]
        app.launch()
    }

    func testMainAppScreenShown() {
        XCTAssert(app.navigationBars["My App"].exists)
    }
}

One note though: If you are using SwiftyUserDefaults library, this solution wouldn't work. There is a problem in the current version of the library where converting YES and NO strings to true and false is not working as expected. There was a PR that solved this problem (that is rejected), but to solve this problem, you can look at the solutions #2 and #3 from this answer.