XCTest UI: How to clear application data that uses Realm

  1. 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 XCTestoverride 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 followingfunc 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()
                  }
              }
      }
  2. 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 methodfunc purgeRealm() {
          NSFileManager.defaultManager().removeItemAtPath(RLMRealm.defaultRealmPath(), error: nil)
      }