XCTest UI: How to clear application data that uses Realm
Опубликовано вс, 08/06/2017 - 13:42 пользователем Nikolai- If the application use the Realm db and don't use CoreData you can clear the application data using the following way.
- Just add the environment to setUp method of the XCTest
override func setUp() {
super.setUp()
let application = XCUIApplication()
application.launchEnvironment = ["XCUITEST":"1"]
application.launch()
} - In the application go to the class with method application and add the following
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let env = ProcessInfo.processInfo.environment
if let uiTests = env["XCUITEST"], uiTests == "1" {
let realmManager = RealmManager()
let realm = realmManager.getRealmInstance()
try! realm?.write {
realm?.deleteAll()
}
}
}
- Just add the environment to setUp method of the XCTest
- In case if the application uses the CoreData you can just remove all entity objects
func deleteRecords() -> Void {
let moc = getContext()
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")
let result = try? moc.fetch(fetchRequest)
let resultData = result as! [Person]
for object in resultData {
moc.delete(object)
}
do {
try moc.save()
print("saved!")
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
} catch {
}
}
func getContext () -> NSManagedObjectContext {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.persistentContainer.viewContext
}- Also, remove Realm db via CoreData can be performed with follow method
func purgeRealm() {
NSFileManager.defaultManager().removeItemAtPath(RLMRealm.defaultRealmPath(), error: nil)
}