How to mock data in UITest on Xcode 7?
Asked Answered
S

1

10

Someone has tried to include mock data with the new Xcode 7 UI tests?

  • Have you used an specific framework?
  • How have you managed targets?
Scald answered 14/7, 2015 at 10:10 Comment(0)
P
9

I think there are a lot of ways to approach this one - the difficulty is that Apple has intentionally designed UITests to run entirely separate from the app under test. That said, there are a few hooks you can use to coordinate logic in the app with logic in your tests to feed in mock data or alter the behavior of your app in any way. The two I have found most useful are launchEnvironment and launchArguments.

in your test - XCUIApplication().launchArguments corresponds to NSProcessInfo.processInfo().arguments in your app code

likewise: XCUIApplication().launchEnvironment -> NSProcessInfo.processInfo().environment

launchEnvironment is a straight forward dictionary whereas launch arguments is an array. In your test you can feed any values you like into either of these parameters before you launch the app:

let app = XCUIApplication()
app.launchEnvironment["-FakedFeedResponse"] = "success.json"
app.launch()

Then in your application logic you can switch on these values however you like. Something like:

func fetchFeed() -> JSON {
    if let fakedJSONFilename = NSProcessInfo.processInfo().environment["-FakedFeedResponse"] {
        let fakePayload = fakeDataFileNamed(fakedJSONFilename)
        return fakePayload
    } else {
       //Make network call and return a real JSON payload 
    }
}

Using this pattern your faked/mock data will need to be files included as members of the app target.

Parsonage answered 20/11, 2015 at 0:18 Comment(2)
Thank you! I just spent several hours trying to pass arguments into the app target and this did the trick.Pilate
It's plain stupid to pollute your code with test-related code, e.g in this case checking if its a fake feed or should be fetched from server...Marucci

© 2022 - 2024 — McMap. All rights reserved.