My application is currently using Core Data as the persistence and I want to do some UI testing with some mock data. Currently I am running the UI tests with the data stored previously whilst developing. Ideally I would like to insert some mock data into the MOC to allow me to write more UI tests. For my unit tests, I am inserting data from a JSON file into the managed object context in the setup function. I want to know if this is possible for UI tests?
I have tried looking this up online, but I have read so many different answers from people that I am just confused now. If this is not possible, could anyone recommend the best practice for UI testing with core data?
It is not possible to create the mockup data inside your UITest classes, because the UITest classes cannot access your app's code.
From Apple's Docs:
UI testing differs from unit testing in fundamental ways. Unit testing enables you to work within your app's scope and allows you to exercise functions and methods with full access to your app's variables and state. UI testing exercises your app's UI in the same way that users do without access to your app's internal methods, functions, and variables. This enables your tests to see the app the same way a user does, exposing UI problems that users encounter.
If you want to use mock data when running UITests you have create the mock data inside your app's code and then make sure the mock data is only created when running UITests.
To make that work you have to do the following steps:
1) Add a launch argument when launching your app in your UITest class:
func testExample() {
let app = XCUIApplication()
app.launchArguments.append("IS_RUNNING_UITEST")
app.launch()
// Do your tests
}
2) Add the code that creates the mock data to your app (e.g. in your AppDelegate
) and run it when the launch argument is present:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if ProcessInfo.processInfo.arguments.contains("IS_RUNNING_UITEST") {
// insert data from a JSON file into the managed object context
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With